1

我有下表,并希望使用 sum 聚合在多列上使用数据透视。

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

使用单一查询。不使用任何循环

谢谢

4

2 回答 2

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;
于 2013-08-26T12:55:19.150 回答
0

您可以通过先取消旋转、 和列station1,然后应用 PIVOT 函数来获得结果。unpivot 过程将多列数据转换为多行。station2station3

有几种方法可用于取消透视数据,包括 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 |
于 2013-08-26T16:03:07.563 回答