sql笔记-计算每月累计销售额

1、先计算店铺每月的销售额,店铺、月份、销售额,建立临时表a。
2、通过自连接的方式将表a自连接,以店铺名为匹配条件,得到每个店铺每个月与该店铺其他月份的连接结果。得到表b。
3、筛选表b中某店铺前一个月份列大于等于后一个月份列的记录,对金额做sum聚合,得到该店铺该月份的累计值,group by字段为店铺名、前一个月份列、当月金额值。得到结果表c。

1)按照商店名称和月份进行分组统计:
create table tmp_store1 as
select name,months,sum(money) as money from t_store group by name,months;
2)对tmp_store1 表里面的数据进行自连接:
create table tmp_store2 as
select a.name aname,a.months amonths,a.money amoney,b.name bname,b.months bmonths,b.money bmoney from tmp_store1 a
join tmp_store1 b on a.name=b.name order by aname,amonths;
3)比较统计:
select aname,amonths,amoney,sum(bmoney) as total from tmp_store2 where amonths >= bmonths group by aname,amonths,amoney;

你可能感兴趣的:(sql笔记)