2016-11-29 81 views
0

我想比较本月每日订单数与上个月每日订单数之间的差异,并使用postgresql sql查询将它们按天分组。比较当前月份的订单每日计数与最近一次飞蛾的每日计数

例子:

1st of nov count - 1st of oct count

+0

好了,一个好办法,开始这样的查询是用'SELECT'。 –

+0

@Riv我知道如何获得当天和上个月按日分组的日常订单。我的问题是如何比较每一天计数与过去一个月的等值,我不知道如何。我猜测自我加入或者什么可能会帮助,但我不知道。 – bsh

+0

@GordonLinoff是不是总是:) – bsh

回答

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 
相关问题