在只有两列(id
和dt
)的表格中,我想计算过去3天内登录的唯一user_id的数量(dt是登录日期)对于任何给定的日期。这是我的数据样本:
id dt
user_10 2015-09-01
user_9 2015-09-01
user_4 2015-09-01
user_8 2015-09-01
user_8 2015-09-02
user_9 2015-09-02
user_1 2015-09-02
user_6 2015-09-02
user_7 2015-09-03
user_3 2015-09-03
user_8 2015-09-03
user_10 2015-09-03
user_10 2015-09-04
user_9 2015-09-04
user_8 2015-09-04
user_4 2015-09-04
user_8 2015-09-04
user_6 2015-09-04
预期的输出是:
day count
2015-09-01 3
2015-09-02 5
2015-09-03 7
2015-09-04 8
以下是带有此数据的sqlfidle链接:http://sqlfiddle.com/#!9/ecda9
我尝试了几种方法,但我只能在数据的第一天得到正确的结果:
select t1.dt, count(distinct(t1.id)) from t as t1 INNER JOIN t t2
ON datediff(t1.dt,t2.dt)<=2
GROUP BY t1.dt
order by t1.dt
答案 0 :(得分:1)
SELECT a.dt
, COUNT(DISTINCT b.id) n
FROM t a
JOIN t b
ON b.dt BETWEEN a.dt - INTERVAL 3 DAY AND a.dt
GROUP
BY a.dt;
或调整您的解决方案......
select t1.dt
, count(distinct(t2.id))
from t as t1
JOIN t t2
ON datediff(t1.dt,t2.dt) BETWEEN 0 AND 2
GROUP
BY t1.dt
order
by t1.dt;