0

我想创建一个查询来按月获取我们活跃客户的累积总和。这里的棘手之处在于(不幸的是)一些客户流失了,所以我需要在他们离开我们的当月将他们从累积金额中删除。

这是我的客户表的示例:

customer_id |   begin_date  |   end_date
-----------------------------------------
1           |   15/09/2017  |   
2           |   15/09/2017  |   
3           |   19/09/2017  |   
4           |   23/09/2017  |   
5           |   27/09/2017  |   
6           |   28/09/2017  |   15/10/2017
7           |   29/09/2017  |   16/10/2017
8           |   04/10/2017  |   
9           |   04/10/2017  |   
10          |   05/10/2017  |   
11          |   07/10/2017  |   
12          |   09/10/2017  |   
13          |   11/10/2017  |   
14          |   12/10/2017  |   
15          |   14/10/2017  |

这是我想要实现的目标:

month   |   active customers
-----------------------------------------       
2017-09 |   7
2017-10 |   6

我已经设法通过以下查询实现了它......但是,我想知道是否有更好的方法。

select 
    "begin_date" as "date",
    sum((new_customers.new_customers-COALESCE(churn_customers.churn_customers,0))) OVER (ORDER BY new_customers."begin_date") as active_customers
FROM (
    select 
        date_trunc('month',begin_date)::date as "begin_date",
        count(id) as new_customers
    from customers
    group by 1
) as new_customers
LEFT JOIN(
    select 
        date_trunc('month',end_date)::date as "end_date",
        count(id) as churn_customers
    from customers
    where
        end_date is not null
    group by 1
) as churn_customers on new_customers."begin_date" = churn_customers."end_date"
order by 1
;
4

1 回答 1

0

您可以使用 CTE 来计算总数end_dates,然后使用左连接从开始日期的计数中减去它

SQL小提琴

查询 1

WITH edt
AS (
    SELECT to_char(end_date, 'yyyy-mm') AS mon
        ,count(*) AS ct
    FROM customers
    WHERE end_date IS NOT NULL
    GROUP BY to_char(end_date, 'yyyy-mm')
    )
SELECT to_char(c.begin_date, 'yyyy-mm') as month
    ,COUNT(*) - MAX(COALESCE(ct, 0)) AS active_customers
FROM customers c
LEFT JOIN edt ON to_char(c.begin_date, 'yyyy-mm') = edt.mon
GROUP BY to_char(begin_date, 'yyyy-mm')
ORDER BY month;

结果

|   month | active_customers |
|---------|------------------|
| 2017-09 |                7 |
| 2017-10 |                6 |
于 2018-07-03T11:41:56.273 回答