将行转置为SQL Server 2015列

时间:2018-05-15 07:50:09

标签: sql sql-server sql-server-2012

需要帮助将数据从行转置为列

col1  col2   col3
-------------------
d1    d2      d3

结果应为

col
----
d1
d2
d3

3 个答案:

答案 0 :(得分:2)

使用交叉应用

;WITH CTE(col1,col2,col3)
AS
(
SELECT 'd1','d2','d3'
)
SELECT col FROM CTE
CROSS APPLY (VALUES(col1),(col2),(col3)) As Dt (col);

结果,看看演示:http://rextester.com/LVXO57980

col
---
d1
d2
d3

答案 1 :(得分:1)

你可以用这个:

SELECT col1 AS col
FROM table_name
UNION ALL 
SELECT col2 AS col
FROM table_name
UNION ALL 
SELECT col3 AS col
FROM table_name
ORDER BY col;

答案 2 :(得分:1)

使用此

Select col 
from tablename 
     unpivot ( 
        col
        FOR unpivot_columns IN ([col1],[col2],[col3])
     ) as unpvt;

将此link用于UNPIVOT示例