查找从datetime开始的连续条纹和当前条纹的最大值



我有一个特定用户的以下数据-表temp -

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

Max streak = 4 because of these -

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

当前连胜数是2,因为这些(假设今天的日期是2015-07-19)-

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

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

对于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;

空白和岛屿查询的一般方法是用其在数据中的排名和在完整日期列表中的排名标记每一行。所有集群都具有相同的差异。

警告:我不知道这个查询是否有效。我不记得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

相关内容

  • 没有找到相关文章

最新更新