查看计数列并将值从单行转换为多行

时间:2017-04-20 13:56:18

标签: sql-server-2008 view

我在SQL Server 2008中有这个表T,我需要创建一个视图,将每行的结果转换为多行。以下是目标视图的示例。

请帮忙

当前表格T

EmpID   EmpName State   City
---------------------------------
1234    aaaa     NY     NY
6789    bbbb     FL     Orlando

目标视图:

EmpID   ColumnName      ColumnValue
-----------------------------------
1234    EmpName         aaaa
1234    State           NY
1234    City            NY
6789    EmpName         bbbb
6789    State           FL
6789    City            Orlando

1 个答案:

答案 0 :(得分:0)

CREATE VIEW yourView AS
SELECT EmpID, 'EmpName' AS ColumnName, EmpName AS ColumnValue
FROM T
UNION ALL
SELECT EmpID, 'State', State
FROM T
UNION ALL
SELECT EmpID, 'City', City
FROM T

然后在您从此视图中实际选择时提供排序:

SELECT t.EmpID, t.ColumnName, t.ColumnValue
FROM yourView t
ORDER BY t.EmpID,
         CASE WHEN t.ColumnName = 'EmpName' THEN 1
              WHEN t.ColumnName = 'State'   THEN 2
              WHEN t.ColumnName = 'City'    THEN 3 END