SQL查询; 水平与垂直(SQL query ; horizontal to vertical)

2019-09-22 14:57发布

我坚持用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了分区。 但它不以某种方式工作!

谢谢 !!!

Answer 1:

您可以使用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拨弄演示



文章来源: SQL query ; horizontal to vertical