2013-08-26 46 views
0

我有下面的表,並希望使用總和聚合多列上的樞軸。在多列SQL服務器上的樞軸

Category  Station1   Station2   Station3 
------------------------------------------------------------- 
Category1  5.26    6.25    7.28 
Category2  4.22    5.00    6.00 
Category3  5.00    4.00    8.00 
Category1  4.00    7.00    9.00 
Category2  2.00    5.00    8.00 

,並希望類似的輸出

My_Station   Category1   Category2    Category3 
------------------------------------------------------------------------ 
Station1   Sum_of_Cat1   Sum_of_Cat2   Sum_of_Cat3 
Station2   Sum_of_Cat1   Sum_of_Cat2   Sum_of_Cat3 
Station3   Sum_of_Cat1   Sum_of_Cat2   Sum_of_Cat3 

隨着單個查詢。不使用任何迴路

謝謝

回答

0

這不完全是一個關鍵。你可以untivot和repivot。我傾向於只寫SQL做到這一點:

select station as MyStation, 
     sum(case when category = 'Category1' then value else 0 end) as Category1, 
     sum(case when category = 'Category2' then value else 0 end) as Category2, 
     sum(case when category = 'Category3' then value else 0 end) as Category3 
from (select n.station, t.category, 
      (case when station = 'Station1' then Station1 
        when station = 'Station2' then Station2 
        when station = 'Station3' then Station3 
       end) as value 
     from t cross join 
      (select 'Station1' as station union all select 'Station2' union all select 'Station3') n 
    ) t 
group by station; 
0

您可以通過unpivoting列station1station2得到的結果,並station3第一,然後再進行旋轉功能。 unpivot進程將多列數據轉換爲多行。

有幾種方法可用於未轉移數據,包括UNPIVOT函數,UNION ALL查詢或使用CROSS APPLY。你沒有指定你使用的是什麼版本的SQL Server,但我實現了跨與UNION應用所有因此代碼:

select category, my_station, value 
from yourtable 
cross apply 
(
    select 'station1', station1 union all 
    select 'station2', station2 union all 
    select 'station3', station3 
) c (my_station, value); 

SQL Fiddle with Demo。這給出了以下結果:

| CATEGORY | MY_STATION | VALUE | 
| Category1 | station1 | 5.26 | 
| Category1 | station2 | 6.25 | 
| Category1 | station3 | 7.28 | 
| Category2 | station1 | 4.22 | 
| Category2 | station2 |  5 | 

正如您所看到的多站列現在在行中。然後,您可以將旋轉功能的category值轉換爲列:

select my_station, category1, category2, category3 
from 
(
    select category, my_station, value 
    from yourtable 
    cross apply 
    (
    select 'station1', station1 union all 
    select 'station2', station2 union all 
    select 'station3', station3 
) c (my_station, value) 
) d 
pivot 
(
    sum(value) 
    for category in (category1, category2, category3) 
) piv; 

SQL Fiddle with Demo。這給出了最終結果:

| MY_STATION | CATEGORY1 | CATEGORY2 | CATEGORY3 | 
| station1 |  9.26 |  6.22 |   5 | 
| station2 |  13.25 |  10 |   4 | 
| station3 |  16.28 |  14 |   8 |