从日期时间中查找连续条纹的最大值和当前条纹

时间:2015-07-18 23:59:04

标签: mysql sql database gaps-and-islands

我有特定用户的以下数据 - 表格温度 -

time_stamp
2015-07-19 10:52:00
2015-07-18 10:49:00
2015-07-12 10:43:00
2015-06-08 12:32:00
2015-06-07 11:33:00
2015-06-06 10:05:00
2015-06-05 04:17:00
2015-04-14 04:11:00
2014-04-02 23:19:00

所以查询的输出应该是 - Maximum streak = 4, Current streak = 2

最大条纹= 4因为这些 -

2015-06-08 12:32:00
2015-06-07 11:33:00
2015-06-06 10:05:00
2015-06-05 04:17:00

目前的连胜纪录是因为这些(假设今天的日期是2015-07-19) -

2015-07-19 10:52:00
2015-07-18 10:49:00

编辑:我想要一个简单的SQL查询MYSQL

2 个答案:

答案 0 :(得分:0)

使用间隙和孤岛查询的一般方法是用数据中的排名标记每一行,并在完整的日期列表中标记其排名。群集将具有相同的差异。

警告:我不知道这个查询是否有效。我不记得MySQL是否允许标量子查询。我没有查找计算MySQL中的日间隔的方法。

select user_id, max(time_stamp), count(*)
from (
    select
        t.user_id, t.time_stamp,
        (
            select count(*)
            from T as t2
            where t2.user_id = t.user_id and t2.time_stamp <= t.time_stamp
        ) as rnk,
        number of days from t.time_stamp to current_date as days
    from T as t

) as data
group by usr_id, days - rnk

答案 1 :(得分:0)

对于MAX streak(streak),您可以使用它,我使用相同的查询来计算最大条纹。这可能对您有帮助

SELECT *
FROM (
   SELECT t.*, IF(@prev + INTERVAL 1 DAY = t.d, @c := @c + 1, @c := 1) AS streak, @prev := t.d
   FROM (
       SELECT date AS d, COUNT(*) AS n
       FROM table_name
       group by date

   ) AS t
   INNER JOIN (SELECT @prev := NULL, @c := 1) AS vars
) AS t
ORDER BY streak DESC LIMIT 1;