简体   繁体   English

MySQL Select Day Streak

[英]MySQL Select Day Streak

This question is similar to the one answered here: http://sqlfiddle.com/#!2/929846/1/0 这个问题类似于这里回答的问题: http//sqlfiddle.com/#!2/929846/1/0

Id    UserId  Timestamp
1     1       2012-12-01
2     2       2012-12-02
3     1       2012-12-02
4     2       2012-12-02
5     1       2012-12-03
6     3       2012-12-02
7     2       2012-12-03
8     3       2012-12-03

I'd like to retrieve the current streak for a user 1 . 我想检索用户1的当前条纹。 The expected result is 3 if today's date is 2012-12-03 . 如果今天的日期是2012-12-03 ,预期结果为3

The user will never have more than one entry in the same space of 24 hours. 用户在24小时的同一空间内永远不会有多个条目。

If they have 4 records, their streak is 4. If they have 2 records, their streak is 2. If their last record is more than 24 hours ago, their streak is 0. 如果他们有4条记录,他们的连胜数是4.如果他们有2条记录,他们的连胜是2.如果他们的最后一次记录超过24小时前,他们的连胜是0。

How can I calculate the streak using just a MySQL query? 如何仅使用MySQL查询来计算条纹?

Rephrase 另一种方式

A "streak" is defined as the number of consecutive days ( Timestamp ) having an entry for a given UserId . “条纹”被定义为具有给定UserId的条目的连续天数( Timestamp )。

Need help writing sql (or maybe a Stored Function) that, given a UserId and an ending Timestamp , returns the streak . 需要帮助编写sql(或者可能是存储函数),给定UserId和结束Timestamp ,返回streak

You can use the following query: 您可以使用以下查询:

SELECT MAX(streak) AS streak
FROM (
  SELECT Id, UserId, `Timestamp`,
         DATEDIFF(NOW(), `Timestamp`),
         @streak := IF( DATEDIFF(NOW(), `Timestamp`) - @days_diff > 1, @streak, 
                       IF(@days_diff := DATEDIFF(NOW(), `Timestamp`), @streak+1, @streak+1))  AS streak                                        
  FROM mytable
  CROSS JOIN (SELECT @streak := 0, @days_diff := -1) AS vars
  WHERE UserId = 1 AND `Timestamp` <= NOW()
  ORDER BY `Timestamp` DESC) AS t

The query uses @streak variable to incrementally update the streak number. 该查询使用@streak变量逐步更新条纹数。 The variable keeps being incremented as long as there is no gap bigger than one day between two consecutive records. 只要两个连续记录之间没有大于一天的间隙,变量就会不断增加。

Note that @days_diff is initialized to -1 so that if the last record, which is processed first , is more than 24 hours ago, the streak is set to 0 . 需要注意的是@days_diff被初始化为-1 ,这样,如果最后一个记录,这是第一个被处理的,超过24小时前,连胜被设置为0

Demo here 在这里演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM