我有一个表格,显示每个日期的客户 ID 列表 - 显示在任何特定日期活跃的客户。因此每个日期都可以包含在另一个日期中也存在的 ID。
bdate customer_id
2012-01-12 111
2012-01-13 222
2012-01-13 333
2012-01-14 111
2012-01-14 333
2012-01-14 666
2012-01-14 777
我想编写一个查询来计算两个日期之间唯一 ID 的总数 - 开始日期是行日期,结束日期是 future 的特定日期。
我的查询是这样的:
select
bdate,
count(distinct customer_id) as cts
from users
where bdate between bdate and current_date
group by 1
order by 1
但这会产生每个日期的唯一用户数,如下所示:
bdate customer_id
2012-01-12 1
2012-01-13 2
2012-01-14 4
我想要的结果是(开始行日期和 2012-01-14 之间的用户数)
bdate customer_id
2012-01-12 5 - includes (111,222,333,666,777)
2012-01-13 5 - includes (222,333,111,666,777)
2012-01-14 4 - includes (111,333,666,777)
最佳答案
赞@Strawberry说,你可以像这样加入:
select
t1.bdate,
count(distinct t2.customer_id) as cts
from users t1
join users t2 on t2.bdate >= t1.bdate
where t1.bdate between t1.bdate and current_date
group by t1.bdate
order by t1.bdate
加入 t2 可以获得特定日期和 current_date
之间的所有用户,然后 count
t2 的 customer_id
,就是这样。
关于mysql - 按发行日期累计计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40731953/