我有一张表格,显示每个日期的客户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的总数 - 开始日期是行日期,结束日期是将来的特定日期。
我的查询如下:
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)
答案 0 :(得分:0)
就像@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
为您提供所有用户,就是这样。