diff --git a/lib/badge_queries.rb b/lib/badge_queries.rb index 515e44cfa88..dd70192c08b 100644 --- a/lib/badge_queries.rb +++ b/lib/badge_queries.rb @@ -235,15 +235,20 @@ SQL def self.consecutive_visits(days) <<~SQL WITH consecutive_visits AS ( - SELECT user_id, visited_at - (DENSE_RANK() OVER (PARTITION BY user_id ORDER BY visited_at))::int "start" + SELECT user_id + , visited_at + , visited_at - (DENSE_RANK() OVER (PARTITION BY user_id ORDER BY visited_at))::int s FROM user_visits ), visits AS ( - SELECT user_id, "start", DENSE_RANK() OVER (PARTITION BY user_id ORDER BY "start") "rank" + SELECT user_id + , MIN(visited_at) "start" + , DENSE_RANK() OVER (PARTITION BY user_id ORDER BY s) "rank" FROM consecutive_visits - GROUP BY user_id, "start" + GROUP BY user_id, s HAVING COUNT(*) >= #{days} ) - SELECT user_id, "start" + interval '#{days} days' "granted_at" + SELECT user_id + , "start" + interval '#{days} days' "granted_at" FROM visits WHERE "rank" = 1 SQL