如何使用数据透视表将行转换为列

时间:2018-11-13 08:50:06

标签: sql sql-server

我的桌子上有这样的数据

A|B|C|D|E|
----------
100|ABC|OL|Decmber|100
100|ABC|OL|January|200
100|ABC|OL|February|290
100|DEF|OL|Decmber|260
100|DEF|OL|January|300
100|DEF|OL|February|360
200|ABC|OL|December|500
200|ABC|OL|January|600
200|ABC|OL|February|550
200|DEF|OL|December|570
200|DEF|OL|January|600
200|DEF|OL|February|680
----------

我希望输出应为

A|B|C|December|January|February
100|ABC|OL|100|290|300
100|DEF|OL|200|260|360
200|ABC|OL|500|550|600
200|DEF|OL|600|570|680

因为值是动态的,所以我有以下查询:-

DECLARE @cols NVARCHAR(MAX), @query NVARCHAR(MAX);
SET @cols = STUFF(
             (
                 SELECT Distinct
                        ','+QUOTENAME(c.[D])
                 FROM #rolling  c FOR XML PATH(''), TYPE
             ).value('.', 'nvarchar(max)'), 1, 1, '');
SET @query = 'SELECT [A],[B],[C],'+@cols+'from (SELECT [A] ,[B],[C],

[D] as [Month],  


  [E] as [amount]
FROM #rolling
)x pivot (min(amount) for Month in ('+@cols+'))p';
EXECUTE (@query);

但是我得到的输出是这样的。

A|B|C|ABC|DEF|
100|December|OL|100|200
100|January|OL|290|260
100|February|OL|300|360
200|December|OL|500|600
200|January|OL|550|570
200|February|OL|600|680

由于该表中的月份名称是动态的,所以我使用了此名称。 但是我得到的输出就是这样。 请帮助我如何实现前面提到的结果。

1 个答案:

答案 0 :(得分:0)

您可以在下面尝试-使用STUFF()函数时,看来您的dbms是SQL SERVER

DEMO

declare @sql varchar(max)='',@col_list varchar(8000)=''

set @col_list = (select distinct quotename([D])+',' from #rolling
for xml path(''))

set @col_list = left (@col_list,len(@col_list)-1)

set @sql = 'select A,B,C,'+@col_list+' from
#rolling
pivot (max([E]) for [D] in ('+@col_list+'))pv'

exec(@sql)

输出:

    A   B   C   December    February    January
   100  ABC OL    100        290         200
   100  DEF OL    260        360         300
   200  ABC OL    500        550         600
   200  DEF OL    570        680         600