I'm trying to determine the most consecutive days for history
. I tried to use the solution from here, but for some reason I receive nil
.
I know that there are other solutions with SQL like here, but SQL is not my strong suit.
I need to find what was the longest consecutive streak of histories for a user without interruption (any number of days with no history will break the streak).
Table example:
Class History
user_id: 1, created_at: '2018-01-02' # streak 1 #=> start
user_id: 1, created_at: '2018-01-03' # streak 2
user_id: 1, created_at: '2018-01-04' # streak 3
user_id: 1, created_at: '2018-01-04' # streak 3 #=> end
user_id: 1, created_at: '2018-01-06' # streak 1 #=> start and end
user_id: 1, created_at: '2018-01-08' # streak 1 #=> start
user_id: 1, created_at: '2018-01-09' # streak 2 #=> end
user_id: 1, created_at: '2018-01-11' # streak 1 #=> start and end
user_id: 1, created_at: '2018-01-17' # streak 1 #=> start
user_id: 1, created_at: '2018-01-18' # streak 2
user_id: 1, created_at: '2018-01-19' # streak 2
user_id: 1, created_at: '2018-01-20' # streak 3
user_id: 1, created_at: '2018-01-21' # streak 4
user_id: 1, created_at: '2018-01-22' # streak 5 # end # the longest steak 5 I need to receive 5
user_id: 1, created_at: '2018-01-25' # ...
I need to receive the number 5 as its the longest streak (5 days in a row). It would also be nice to find the start day and end day of the longest streak, but not a must.
Here is what I tried:
qry = <<-SQL
SELECT (CURRENT_DATE - series_date::date) AS days
FROM generate_series(
( SELECT created_at::date FROM histories
WHERE histories.user_id = :user_id
ORDER BY created_at
ASC LIMIT 1
),
CURRENT_DATE,
'1 day'
) AS series_date
LEFT OUTER JOIN histories ON histories.user_id = :user_id AND
histories.created_at::date = series_date
GROUP BY series_date
HAVING COUNT(histories.id) = 0
ORDER BY series_date DESC
LIMIT 1
SQL
History.find_by_sql([ qry, { user_id: current_user.id } ])
But the response is:
# => [#<History id: nil>]
Maybe it's because I am using Postgres, but I ran it through the converter, so its looks ok. Or not?
I would really appreciate any working solution for this problem.