我想比较本月每日订单数量与上个月每日订单数量之间的差异,并使用postgresql sql查询按天分组。
示例:
1st of nov count - 1st of oct count
答案 0 :(得分:0)
只需计算上个月的日期并加入
create table sales (
d DATE
,orederCount INT
);
INSERT INTO sales(d, orederCount) VALUES ('2016-11-01',12),('2016-10-01',10),('2016-09-01',10)
,('2016-11-02',13),('2016-10-02',14),('2016-09-02',5);
with data as (select d,(d-INTERVAL '1 month')::DATE as p,orederCount from sales)
select current.d,current.orederCount - COALESCE(prev.orederCount,0) as diff
from data as current
LEFT JOIN data as prev ON current.p = prev.d
;
结果:
2016-09-01,10
2016-09-02,5
2016-10-01,0
2016-10-02,9
2016-11-01,2
2016-11-02,-1