连续付款的客户

时间:2018-07-20 11:02:12

标签: sql postgresql window-functions

我不确定这是否可以在PostgreSQL上完成,我有一张表格,上面有customer_idpaid_at(付款月份),我如何才能找到连续为最后付款的公司(自2018年1月起)的6个月内,以及从第一笔付款(min(paid_on))开始一直连续付款的公司中的哪些公司?

     customer_id    paid_on
       14535    01/04/2018
       21828    01/10/2017
       52159    01/10/2017
       35033    01/02/2018
       1686     01/08/2016
       7347     01/02/2018
       33721    01/01/2018
       25789    01/07/2017
       62237    01/01/2018
       46184    01/02/2018

1 个答案:

答案 0 :(得分:2)

示例数据:

create table payments(customer_id int, paid_on date);
insert into payments values
    (1, '2018-03-01'),
    (1, '2018-04-01'),
    (1, '2018-06-01'),
    (1, '2018-07-01'),
    (2, '2018-01-01'),
    (2, '2018-04-01'),
    (2, '2018-05-01'),
    (2, '2018-06-01'),
    (2, '2018-07-01'),
    (3, '2018-03-01'),
    (3, '2018-04-01');

该查询为您提供有关上一次付款的月份,上一个系列中连续支付的月份数以及所有支付的月份数的信息:

select 
    customer_id, 
    max(paid_on) as last_payment, 
    count(*) filter (where sum = 0) as consecutive_months,
    count(*) as all_months
from (
    select 
        customer_id, paid_on, 
        sum(grp) over w
    from (
        select 
            customer_id, paid_on, 
            (paid_on <> lag((paid_on- '1 month'::interval)::date, 1, paid_on) over w)::int as grp
        from payments
        window w as (partition by customer_id order by paid_on desc)
        ) s
    window w as (partition by customer_id order by paid_on desc)
    ) s
group by 1

 customer_id | last_payment | consecutive_months | all_months 
-------------+--------------+--------------------+------------
           1 | 2018-07-01   |                  2 |          4
           2 | 2018-07-01   |                  4 |          5
           3 | 2018-04-01   |                  2 |          2
(3 rows)