2012-07-05 90 views
2

我有數據格式如下在TSQL與Sum函數樞軸

Client  Business Unit Year Quarter  USD Amt 
BalckRock Pricing   2010 Q1   234 
BalckRock Pricing   2010 Q2   343 
BalckRock Pricing   2010 Q3   545 
BalckRock Pricing   2010 Q4   5435 
BalckRock Pricing   2011 Q1   5425 
BalckRock Pricing   2011 Q2   3524 
BalckRock Pricing   2011 Q3   54 
BalckRock Pricing   2011 Q4   5425 
BalckRock Pricing   2012 Q1   545 
BalckRock Pricing   2012 Q2   5445 
BalckRock Pricing   2012 Q3   545 
BalckRock Pricing   2012 Q4   4545 
BalckRock Sales   2010 Q1   23 
BalckRock Sales   2010 Q2   3434 
BalckRock Sales   2010 Q3   4234 
BalckRock Sales   2010 Q4   4234 
BalckRock Sales   2011 Q1   3423 
BalckRock Sales   2011 Q2   1 
BalckRock Sales   2011 Q3   1341 
BalckRock Sales   2011 Q4   434 
BalckRock Sales   2012 Q1   421 
BalckRock Sales   2012 Q2   42 
BalckRock Sales   2012 Q3   434 
BalckRock Sales   2012 Q4   4214 

而且我想在下面的格式

Client  Business Unit 2010 2011 2012 
BalckRock  Pricing   6557 14428 11080 
BalckRock  Sales   11925 5199 5111 

基本上USD amnt全年總和明智的,但年列標題

任何人都可以幫助我嗎?

+0

發佈你現有的sql代碼,你有什麼試過? – 2012-07-05 16:27:30

+0

檢查這個問題的代碼 - http://stackoverflow.com/questions/1122117/sql-dynamic-pivot-how-to-order-columns?rq=1 – 2012-07-05 16:29:45

回答

4

有不同的方式,你可以使用PIVOT(靜態或動態取決於您的需要),也可以簡單地使用CASE

SELECT Client, 
     [Business Unit], 
     SUM(CASE WHEN [Year] = 2010 THEN [USD Amt] ELSE 0 END) [2010], 
     SUM(CASE WHEN [Year] = 2011 THEN [USD Amt] ELSE 0 END) [2011], 
     SUM(CASE WHEN [Year] = 2012 THEN [USD Amt] ELSE 0 END) [2012] 
FROM YourTable 
GROUP BY Client, [Business Unit] 

使用PIVOT

SELECT * 
FROM ( SELECT Client, [Business Unit], [USD Amt], [Year] 
     FROM YourTable) T 
PIVOT (SUM([USD Amt]) FOR [Year] IN ([2010],[2011],[2012])) PT 
2

- 透視一排五列表

SELECT Client Business Unit Year Quarter USD Amt,[2010],[2011],[2012] 
FROM 
(SELECTClient Business Unit Year Quarter USD Amt 
    FROM Table) AS SourceTable 
PIVOT 
(
sum(USD Amt) 
FOR Year IN ([2010], [2011], [2012]) 
) AS PivotTable; 
5

你可以很容易地使用這個PIVOT。正如其他人所說的,你可以使用靜態數據透視表來編碼你想要的列,或者你可以使用動態數據透視表,它可以在運行時獲得列表的列表。

靜態樞軸(見Sql Fiddle for Demo

select * 
from 
(
    select client, businessunit, year, USD_Amount 
    from t 
) x 
pivot 
(
    sum(USD_Amount) 
    for year in ([2010], [2011], [2012]) 
) p 

但對於這一點,我可能會建議一個動態的透視,所以你不必當你進入一個新的一年改變你的代碼。 (見Sql Fiddle with Demo

DECLARE @cols AS NVARCHAR(MAX), 
    @query AS NVARCHAR(MAX) 


select @cols = STUFF((SELECT distinct ',' + QUOTENAME(year) 
        from t 
      FOR XML PATH(''), TYPE 
      ).value('.', 'NVARCHAR(MAX)') 
     ,1,1,'') 

set @query = 'SELECT client, businessunit, ' + @cols + ' from 
      (
       select client, businessunit, year, USD_Amount 
       from t 
      ) x 
      pivot 
      (
       sum(USD_Amount) 
       for year in (' + @cols + ') 
      ) p ' 

execute(@query) 

這兩個查詢都會產生相同的結果。但是,動態數據透視表的優點是,如果您有更多年份的數據,則不必更新查詢以包含這些字段。查詢的第一部分獲取表格中的distinct years列表,然後使用該列表years來確定您正在查找的SUM