0

I am trying to use a query from this SO question Check for x consecutive days - given timestamps in database to count a number of consecutive days a user has submitted an activity i.e. 3 days, 5 days, 7 days etc.

The query is:

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

The code works great when the date field is not dateTime but how would I modify the code to ignore the time component of dateTime? I have tried using DATE(dateAdded) but that didn't work.

My data looks like:

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

Thanks

Community
  • 1
  • 1
puks1978
  • 3,667
  • 11
  • 44
  • 103

1 Answers1

0

Casted the dateAdded field to Date.

Please give it a try and let me know if it resolves the issue:

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;

Note: Using timestamp will return correct output only if they are having same time (hh:mm:ss)

1000111
  • 13,169
  • 2
  • 28
  • 37