我有下表,并希望使用sum aggregate在多列上使用pivot。
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 :(得分:0)
这不完全是一个支点。你可以透视和重新编译。我倾向于只编写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;
答案 1 :(得分:0)
您可以先取消列station1
,station2
和station3
,然后应用PIVOT功能来获得结果。 unpivot进程将多列数据转换为多行。
有几种方法可用于取消数据,包括UNPIVOT函数,UNION ALL查询或使用CROSS APPLY。您没有指定您正在使用的SQL Server版本,但我使用UNION ALL实现了CROSS APPLY,因此代码为:
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 |
正如您所看到的,多站列现在是行。然后,您可以应用PIVOT函数将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 |