SQL实现行列互换

题目:数据库中有一张如下所示的表,表名为sales。

年         季度        销售量
1991       1             11
1991       2             12
1991       3             13
1991       4             14
1992       1              21
1992       2              22
1992       3              23
1992       4              24


要求:写一个SQL语句查询出如下所示的结果。

年    一季度    二季度    三季度    四季度
1991    11          12            13       14
1992    21          22            23       24


我给出的答案是这样的:

select 年, 
sum(case when 季度=1 then 销售量 else 0 end) as 一季度, 
sum(case when 季度=2 then 销售量 else 0 end) as 二季度, 
sum(case when 季度=3 then 销售量 else 0 end) as 三季度, 
sum(case when 季度=4 then 销售量 else 0 end) as 四季度 
from sales group by 年;
--------------------- 
转载:https://blog.csdn.net/jackfrued/article/details/45021897 
 

猜你喜欢

转载自blog.csdn.net/LMAKE_nbsp/article/details/83999581