0
点赞
收藏
分享

微信扫一扫

金额环比增长率-行转列

DT_M 2022-02-06 阅读 38
sparksqlhive

1:SALES表的表数据如下:

yearmonthamt
202104100
202105200
202004400
202005150
201904300
201905
20200450

需求:请写出可以得到以下的结果SQL

year4月份金额5月份金额总金额环比(%)
2020150150600
2021100200300

建表语句:

create table sales(year int ,month string,amt int);
insert into sales values
(2021,'04',100),
(2021,'05',200),
(2020,'04',400),
(2020,'05',150),
(2019,'04',300),
(2019,'05',null),
(2020,'04',50);

分析思路:要实现行转列无非就是===>>>带条件的聚合

--行转列套路===>>>带条件的聚合
select year,
       sum(if(month='04',amt,0)) as amt4,
       sum(if(month='05',amt,0)) as amt5,
       sum(amt) as sum_all

最终SQL:

--行转列的常规套路就是group by+带条件(case when或if)的聚合
select year,
       amt4, amt5, sum_all,
       round((amt5-amt4)/amt4,4)*100 || '%'  as rate
       from
(select year,
       sum(if(month='04',amt,0)) as amt4,
       sum(if(month='05',amt,0)) as amt5,
       sum(amt) as sum_all
from sales group by  year) t;

 结果:

 

 

 

举报

相关推荐

0 条评论