【每日一练:SQL】行转列的运用,统计每年每个季度的销售额(同一行显示)

SQL题:行转列的运用
将下面的数据
年         季度     销售量
2017     1         11
2017     2         12
2017     3         13
2017     4         14
2018     1         21
2018     2         22
2018     3         23
2018     4         24

转换为
年     一季度     二季度     三季度     四季度
2018     21           22         23         24
2017     11           12         13         14

解答:

--创建表
create table tb_sales(year int,season int,sale int);

--插入数据
insert into tb_sales values(2017,1,11);
insert into tb_sales values(2017,2,12);
insert into tb_sales values(2017,3,13);
insert into tb_sales values(2017,4,14);
insert into tb_sales values(2018,1,21);
insert into tb_sales values(2018,2,22);
insert into tb_sales values(2018,3,23);
insert into tb_sales values(2018,4,24);

commit;
--查询数据
select * from tb_sales;
YEAR    SEASON    SALE
2017    1        11
2017    2        12
2017    3        13
2017    4        14
2018    1        21
2018    2        22
2018    3        23
2018    4        24
--统计数据
select year as "年"
       , sum(case season when 1 then sale else 0 end) as "一季度"
       , sum(case season when 2 then sale else 0 end) as "二季度"
       , sum(case season when 3 then sale else 0 end) as "三季度"
       , sum(case season when 4 then sale else 0 end) as "四季度"
  from tb_sales t
 group by t.year;

年    一季度    二季度    三季度    四季度
2018    21        22        23    24
2017    11        12        13    14

注 :

其实这个统计相关简单,需要新手需要注意的是因使用了group函数,需要对case的值也需要使用统计函数;

你可能感兴趣的:(每日一练,蒙夛的每日一练(SQL,逻辑等))