用于将列转换为行的SELECT语句

时间:2015-04-22 21:10:04

标签: sql-server tsql unpivot

我们的结果集有一行,有四列:

value1, value2, value3, value4

我们如何将其转换为包含一行的四行结果集:

value1
value2
value3
value4

2 个答案:

答案 0 :(得分:2)

如果列已知:

SELECT Value FROM(
    SELECT Value = value1
    FROM dbo.TableName
    UNON ALL
    SELECT Value = value2
    FROM dbo.TableName
    UNON ALL
    SELECT Value = value3
    FROM dbo.TableName
    UNON ALL
    SELECT Value = value4
    FROM dbo.TableName
) X
ORDER BY VALUE -- in case you want that

答案 1 :(得分:2)

UNPIVOT数据的另一种方法是使用CROSS APPLY:

select value
from (Your select statement) as x
cross apply
( 
  select 'value1', value1 union all
  select 'value2', value2 union all
  select 'value3', value3 union all
  select 'value4', value4
) c (ColumnName, value);

请参阅Demo