在SQL Server中将行转换为列不起作用?

时间:2016-08-29 13:38:50

标签: sql sql-server tsql pivot

period  providerid  type    volume     subscribers
--------------------------------------------------
Aug-2016    7        1      4027917    117172
Aug-2016    7        2      5325430    232293
Aug-2016    7        3      8722165    236472
Jul-2016    7        1      2981655     97409
Jul-2016    7        2      6449570    147315
Jul-2016    7        3      7702484    206140

我希望我的结果采用这种格式。

period      providerid  SMS     Data    minutes
Aug-2016    7           432142  42342   5454
Jul-2016    7           5454    5454    545

我已尝试过此查询,但无效。

select   
    period, providerid, 1 as SMS, 2 as Data, 3 as minutes
from 
    #P         
pivot
    (sum(volume) for [type] in ([1],[2],[3])) as P

请帮我SQL服务器

3 个答案:

答案 0 :(得分:4)

摆脱subscribers列:

SELECT  [period],
        providerid, 
        [1] as SMS, 
        [2] as [Data], 
        [3] as [minutes]
FROM (
    SELECT [period],providerid, [type], volume
    FROM YourTable         
) as t
PIVOT (
    MAX(volume) FOR [type] in ([1], [2], [3]) 
) as P

输出:

period      providerid  SMS     Data    minutes
Aug-2016    7           4027917 5325430 8722165
Jul-2016    7           2981655 6449570 7702484

答案 1 :(得分:3)

当您使用1 AS SMS时,它会将1读为数字1.相反,您应该告诉它您的意思是列[1]。 此外,我不太确定如何使用列subscribers,因此当您进行透视时,您可能希望将其删除。

即。尝试;

select   period,providerid,[1] as SMS,[2] as Data,[3] as minutes
FROM   (SELECT Period, ProviderID, Type, Volume 
       FROM #P) X         
PIVOT(
   sum(volume)
   FOR [type] in ([1],[2],[3]) 
)as P

答案 2 :(得分:2)

如果使用列名而不是常量,则查询可能会有效:

SELECT period, providerid, [1] as SMS, [2] as Data, [3] as minutes
FROM #P         
PIVOT (sum(volume)
       FOR [type] in ([1], [2], [3]) 
      ) as P;

那就是说,我通常更喜欢将它们写成条件聚合:

select period,
       sum(case when [type] = 1 then volume end) as SMS,
       sum(case when [type] = 2 then volume end) as data,
       sum(case when [type] = 3 then volume end) as minutes
from #p
group by period;