我试图计算所有物品的连续天数。我已经找到了如何连续计算just for one item天数,样本数据
random.uniform(a, b)
会给我这样的结果:
bob 2014-08-10 00:35:22
sue 2014-08-10 00:35:22
bob 2014-08-11 00:35:22
mike 2014-08-11 00:35:22
bob 2014-08-12 00:35:22
mike 2014-08-12 00:35:22
但我需要为所有这样的用户提供:
date_created | streak|
2014-08-10 00:35:22 | 3|
我一直试图从this response修改sql,但我无法让它工作。我很感激任何建议。
答案 0 :(得分:1)
你可以做的一件事是连续几天自己加入桌子并计算它。注意我在计数中添加一个,因为它不计算第一天
SELECT MIN(e.date_created) as date_created, e.username, COUNT(e.username) + 1 AS streak
FROM example e
LEFT JOIN example ee
ON e.username = ee.username
AND DATE(e.date_created) = DATE(DATE_ADD(ee.date_created, INTERVAL -1 DAY))
WHERE ee.username IS NOT NULL
GROUP BY e.username;
答案 1 :(得分:1)
您可以按照以下步骤使用CTE解决此问题,这是sqlfiddle
with ranks as
(
select
date,
name,
dateadd(day, -row_number() OVER (PARTITION BY name ORDER BY date), date) as rr
from orders
),
cnt as
(
select
name,
count(*) as ttl
from ranks
group by
name,
rr
)
select
min(date) as date,
r.name,
ttl
FROM ranks r
join cnt c
on r.name = c.name
where ttl > 1
group by
r.name,
ttl