计算连续天数的最大条纹(数量)

时间:2016-12-27 16:32:34

标签: mysql sql

给定一个包含日期或日期时间列的简单表格,我想在给定可选过滤器的情况下查询行存在的连续天数的最大条纹。

e.g。说一个表有以下列:

  

id,datetime,username,category

我希望能够以最有效的方式查询:

  • 给定用户名的最长条纹(以天为单位),
  • 给定类别中给定用户名的最长条纹(以天为单位),
  • 最长条纹(以天为单位),无论用户名或类别如何,

(我想根据这些过滤器,查询不会有太大变化,但是他们会提出一个想法。)

发现其他类似问题,但似乎没有人回答这个特殊需要,但是请随意将我链接到我可能错过的合适问题。

非常感谢你。

2 个答案:

答案 0 :(得分:1)

SELECT streak
FROM (
    SELECT tb.*, IF(@prev + INTERVAL 1 DAY = tb.d, @count := @count + 1, @count := 1) AS streak, @prev := tb.d
    FROM (
        SELECT datetime AS d
        FROM sometable
        WHERE username = "PWET"
        ORDER BY datetime
    ) AS tb
    INNER JOIN (SELECT @prev := NULL, @count := 1) AS vars
) AS tb
ORDER BY streak DESC LIMIT 1;

来源:http://sonar.example.com/projects

答案 1 :(得分:0)

所以最后答案几乎与现有问题的答案相同:Checking for maximum length of consecutive days which satisfy specific condition

然而,我为了更清晰而重写了它并调整了一些内容:

SELECT streak
FROM (
    SELECT IF(@prevDate + INTERVAL 1 DAY = current.date, @currentStreak := @currentStreak + 1, @currentStreak := 1) AS streak, @prevDate := current.date
    FROM (
        SELECT DATE(datetime) AS date
        FROM mytable
        GROUP BY date
        ORDER BY date
    ) AS current
    INNER JOIN (SELECT @prevDate := NULL, @currentStreak := 1) AS vars
) AS _
ORDER BY streak DESC LIMIT 1;

尽管将这个问题标记为重复似乎是正确的。