计算连续天数(条纹)和当天的记录数

时间:2016-08-28 06:16:06

标签: mysql

以下代码来自另一个关于SO的问题。 Original Q&A

我想计算今天以来记录的连续天数(Streak)以及今天的记录数量。我用这个来发送通知。如果用户在同一天提交新记录,他们就不应该收到第二个通知,告诉他们他们正处于连胜状态(他们在第一次提交当天的记录时就知道了)。

我尝试在COUNT()之后添加@streak函数,在第一个SELECT之后,几乎在任何看似合理的地方都添加了SELECT streak + 1 as realStreak FROM ( SELECT dt, @streak := @streak+1 streak, datediff(curdate(),dt) diff FROM ( SELECT distinct date(dt) dt FROM glucose where uid = 1 ) t1 CROSS JOIN (SELECT @streak := -1) t2 ORDER BY dt desc ) t1 where streak = diff ORDER BY streak DESC LIMIT 1 函数,但这个查询太复杂了,我无法弄明白。

realStreak | RecordsToday
3          |    3

http://sqlfiddle.com/#!9/45d386/1/0

上述结果应为:

function name(args...): result;

1 个答案:

答案 0 :(得分:0)

只需为今日检查添加子查询

SELECT streak + 1 as realStreak,cdt
FROM (
SELECT dt,
@streak := @streak+1 streak, 
datediff(curdate(),dt) diff
FROM (
SELECT distinct date(dt) dt
FROM gl where uid = 1
) t1
CROSS JOIN (SELECT @streak := -1) t2
ORDER BY dt desc
)t1
JOIN
(SELECT COUNT(CASE WHEN DATE(dt)=CURDATE() THEN 1 END) cdt FROM gl)x
where streak = diff
ORDER BY streak DESC LIMIT 1