2016-08-29 39 views
2
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 

我想我的結果在這種格式。在SQL Server中將行轉換爲列不起作用?

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

回答

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 
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; 
+0

通過使用第一個查詢我得到這個結果.................................... ................. –

+0

8 - 2016 \t \t NULL NULL 8 - 2016 \t \t 7 NULL \t \t 5325430 NULL 8 - 2016 \t \t 7 NULL \t NULL Jul-2016 NULL \t NULL 07月2016 \t \t 7 NULL \t \t 6449570 NULL 07月2016 \t \t 7 NULL NULL \t \t 7702484 –

3

當您使用1 AS SMS它讀取1爲數字1。相反,你應該告訴它你的意思列即[1]。 另外,我不太清楚列subscribers是如何使用的,所以當您旋轉時,您可能需要將其刪除。

I.e.嘗試;

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