月份PostgreSQL中按组划分的行数

时间:2017-05-18 08:30:40

标签: sql postgresql

我使用PostgreSQL看起来像这样的数据

customer name       order_id         order_date
John                A001             1-Jan-2017
John                A002             1-Feb-2017
John                A003             1-Apr-2017
Smith               A004             1-Dec-2016
Smith               A005             1-Feb-2017
Jane                A006             1-Mar-2017
Dave                A007             1-Feb-2017
Dave                A008             1-Feb-2017
Dave                A009             1-Feb-2017

我试图在另一栏中找到回购月份之间的差异。就像这样。

customer name       order_id         order_date        month_diff
John                A001             1-Jan-2017        null
John                A002             1-Feb-2017        1
John                A003             1-Apr-2017        2
Smith               A004             1-Dec-2016        null
Smith               A005             1-Feb-2017        3
Jane                A006             1-Mar-2017        null
Dave                A007             1-Feb-2017        null
Dave                A008             1-Feb-2017        0
Dave                A009             1-Feb-2017        0

任何建议都会非常感激。我是postgreSQL的新手。提前谢谢

3 个答案:

答案 0 :(得分:2)

这可以使用窗口函数轻松完成(假设order_date已正确定义为DATE

select customer_name,
       order_id, 
       order_date, 
       order_date - lag(order_date) over (partition by customer_name order by order_date) as diff
from order_table
order by customer_name, order_date;

请注意,如果order_datedate,则差异的结果为天数。

答案 1 :(得分:0)

try with first_value()

select 
customer_name, order_id, order_date
, order_date - first_value(order_date) over (partition by customer_name order by order_id) as month_diff
from tname;

答案 2 :(得分:0)

试试这个:

select
t.customer,
t.order_id,
t.order_date,
(select extract(MONTH from t.order_date) - extract(MONTH from tt.order_date) 
    from your_table tt
    where tt.order_id < t.order_id
    order by tt.order_id desc limit 1
)
from your_table t
order by t.order_id