在 SQL 服务器中将行转换为列不起作用?

Convert row to column in SQL Server does not work?

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服务器

中帮助我

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

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;

去掉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 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