如何PIVOT SQL表

时间:2018-07-09 21:09:49

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

DECLARE @table TABLE
(
id   INT,
dsc  CHAR(30)
)


INSERT INTO @table VALUES (111, 'desc-111-01')
INSERT INTO @table VALUES (111, 'desc-111-02')
INSERT INTO @table VALUES (111, 'desc-111-03')

INSERT INTO @table VALUES (222, 'desc-222-01')
INSERT INTO @table VALUES (222, 'desc-222-02')
INSERT INTO @table VALUES (222, 'desc-222-03')

我需要以这种方式旋转

111 | DESC-111-01 DESC-111-02 DESC-111-03.....
222 | DESC-222-01 DESC-222-02 DESC-222-03.....

谢谢你, BBDS

1 个答案:

答案 0 :(得分:1)

如果您的数据与显示的完全相同(我的意思是它遵循每个ID具有3个描述的模式),则:

select id, 
max(case when rowNo = 1 then dsc else '' end) as dsc1,
max(case when rowNo = 2 then dsc else '' end) as dsc2,
max(case when rowNo = 3 then dsc else '' end) as dsc3
from  
(select id, dsc, 
  row_number() over (partition by id order by dsc) as rowNo from @table) tmp
group by id;

Here is the sample in SQLFiddle