我有一个包含客户ID,注册日期和取消日期的数据集。我想创建一个表,以显示过去12个月中每个月的活跃客户。
我尝试使用this Stack Overflow问题,但无法解决。
如果表格中有一个“月”列和一个活跃客户数列,那就太好了。
欢迎任何帮助。
答案 0 :(得分:0)
编辑*-使用SQL Server的示例
NULL表示客户还没有取消日期,这意味着他非常活跃。
WITH cust (customerid,signupdate,canceldate)
AS
(SELECT 1, '2019-02-10' , '2020-03-05' UNION
SELECT 2, '2018-12-01' , '2019-12-29' UNION
SELECT 3, '2014-04-15' , '2019-09-15' UNION
SELECT 4, '2019-02-10' , '2020-01-04' UNION
SELECT 5, '2020-02-10' , NULL UNION
SELECT 6, '2019-07-10' , '2018-01-01' UNION
SELECT 7, '2019-09-10' , '2020-05-01' UNION
SELECT 8, '2019-02-06' , NULL UNION
SELECT 9, '2018-02-10' , '2020-07-29' UNION
SELECT 10, '2020-02-10' , '2020-04-01'
)
Select CONVERT(CHAR(6),cal.record_date,112) as yyyymm ,
COUNT(DISTINCT c.customerid) as Active_Custs
FROM tbl_Calendar cal
JOIN CUST c ON CONVERT(CHAR(6),cal.record_date,112) BETWEEN CONVERT(VARCHAR(6),cast(c.signupdate as date),112) and CONVERT(CHAR(6),ISNULL(cast(c.canceldate as date),getdate()),112)
GROUP BY CONVERT(CHAR(6),cal.record_date,112)
ORDER BY 1
yyyymm Active_Custs
202007 1
202006 1
202005 4
202004 5
202003 6
202002 6
202001 5
答案 1 :(得分:0)
如果您使用的是Postgres,则可以使用以下内容:
select to_char(g.dt::date, 'yyyy-mm'),
count(c.customer_id) as active_customers
from generate_series(date_trunc('month', current_date) - interval '11 month', date_trunc('month', current_date), interval '1 month') as g(dt)
left join customer c on daterange(c.signup_date, cancel_date) @> g.dt::date
group by to_char(g.dt::date, 'yyyy-mm')
order by 1
这假设您的示例数据中的customer_id = 6
是错误的,因为它的signup_date位于取消日期之后。