SQL查询;水平到垂直

时间:2012-09-19 19:44:04

标签: sql sql-server sql-server-2008 sql-server-2005 unpivot

我遇到了一个涉及将水平行转换为垂直行的SQL查询(SQL Server)

以下是我的数据

No      Flag_1    Flag_2    Flag_3
---      ----      -----     -----
A         1         2         3
B         4         1         6

转换后,表格应为

No     FlagsName    Flag_value
--      ----        ----------
A        Flag_1        1
A        Flag_2        2  
A        Flag_3        3
B        Flag_1        4
B        Flag_2        1
B        Flag_3        6

对此有任何意见会有帮助吗?

我正试图在分区上ROW_NUMBER玩游戏。但它不能以某种方式工作!!!

谢谢!!!

1 个答案:

答案 0 :(得分:12)

您可以使用UNION ALL

select No, 'Flag_1' as FlagName, Flag_1 as Flag_Value
from yourtable
union all
select No, 'Flag_2' as FlagName, Flag_2 as Flag_Value
from yourtable
union all
select No, 'Flag_3' as FlagName, Flag_3 as Flag_Value
from yourtable

UNPIVOT

select no, FlagsName, flag_value
from yourtable
unpivot
(
    flag_value
    for FlagsName in (Flag_1, Flag_2, Flag_3)
) u

请参阅SQL Fiddle With Demo