提问人:Srinivas 提问时间:11/17/2023 最后编辑:Error_2646Srinivas 更新时间:11/17/2023 访问量:34
逐行显示一个记录字段值
Display one record field values into row by row
问:
如何在 SQL 中逐行显示一条记录值。请帮忙
前任:
EMPID EMPNAME EMPADDRESS EMPCOUNTRY
1 TEST HYD INDIA
需要显示如下
ID VALUE
10 TEST
10 HYD
10 INDIA
请注意,10 是另一个唯一的字段值,即单个字段
答:
2赞
Heinz Siahaan
11/17/2023
#1
我假设你使用 .示例代码如下:SQL SERVER
CREATE TABLE Employee (
EMPID INT,
EMPNAME VARCHAR(50),
EMPADDRESS VARCHAR(50),
EMPCOUNTRY VARCHAR(50)
);
INSERT INTO Employee (EMPID, EMPNAME, EMPADDRESS, EMPCOUNTRY)
VALUES (1, 'TEST', 'HYD', 'INDIA');
--10 comes from another table
SELECT 10 AS ID, EMPNAME AS VALUE FROM Employee WHERE EMPID = 1
UNION ALL
SELECT 10 AS ID, EMPADDRESS AS VALUE FROM Employee WHERE EMPID = 1
UNION ALL
SELECT 10 AS ID, EMPCOUNTRY AS VALUE FROM Employee WHERE EMPID = 1;
或者你可以使用UNPIVOT
SELECT
10 AS ID,
COLUMN_VALUE AS VALUE
FROM (
SELECT EMPNAME, EMPADDRESS, EMPCOUNTRY
FROM Employee
WHERE EMPID = 1
) t
UNPIVOT (
COLUMN_VALUE FOR COLUMN_NAME IN (EMPNAME, EMPADDRESS, EMPCOUNTRY)
) unpvt;
输出如下:
您可以检查此小提琴的实现
评论
10