从MySQL数据连续3天获得

时间:2016-07-12 03:25:08

标签: mysql

我正在尝试使用此SO问题Check for x consecutive days - given timestamps in database中的查询来计算用户提交活动的连续天数,即3天,5天,7天等。

查询是:

SELECT IF(COUNT(1) > 0, 1, 0) AS has_consec
FROM
(
SELECT *
FROM
(
    SELECT IF(b.dateAdded IS NULL, @val:=@val+1, @val) AS consec_set
    FROM activity a
    CROSS JOIN (SELECT @val:=0) var_init
    LEFT JOIN activity b ON 
        a.userID = b.userID AND
        a.dateAdded = b.dateAdded + INTERVAL 1 DAY
    WHERE a.userID = 1
) a
GROUP BY a.consec_set
HAVING COUNT(1) >= 3
) a

当日期字段不是dateTime时,代码效果很好但是如何修改代码以忽略dateTime的时间组件?我尝试过使用DATE(dateAdded)但是没有用。

我的数据如下:

userID  dateAdded
1       2016-07-01 17:01:56
1       2016-07-02 12:45:49
1       2016-07-03 13:06:27
1       2016-07-04 12:51:10
1       2016-07-05 15:51:10
2       2016-07-06 16:51:10
2       2016-07-07 11:51:10
1       2016-07-08 11:26:38

由于

1 个答案:

答案 0 :(得分:0)

dateAdded字段转换为Date

请尝试一下,如果它能解决问题,请告诉我:

SELECT IF(COUNT(1) > 0, 1, 0) AS has_consec
FROM
(
SELECT *
FROM
(
    SELECT IF(b.dateAdded IS NULL, @val:=@val+1, @val) AS consec_set
    FROM activity a
    CROSS JOIN (SELECT @val:=0) var_init
    LEFT JOIN activity b ON 
        a.userID = b.userID AND
        DATE(a.dateAdded) = DATE(b.dateAdded) + INTERVAL 1 DAY
    WHERE a.userID = 1
) a
GROUP BY a.consec_set
HAVING COUNT(1) >= 3
) a;

注意:仅当timestamp具有相同的time (hh:mm:ss)

时,才会使用select * from events where `timestamp` between date_sub(concat(curdate()," 06:00:00"), INTERVAL 1 DAY) and concat(curdate()," 05:59:59") 返回正确的输出