Last active
May 22, 2018 14:18
-
-
Save chrisvaughn/a699b7ae846765aa1c75cfd8d1e6ac64 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE "public"."streaks" ( | |
"user_id" int4 NOT NULL, | |
"current_streak" int4 NOT NULL DEFAULT 0, | |
"longest_streak" int4 NOT NULL DEFAULT 0, | |
"last_checkin_dt" date NOT NULL, | |
CONSTRAINT "streaks_pkey" PRIMARY KEY ("user_id") NOT DEFERRABLE INITIALLY IMMEDIATE | |
) | |
-- update query | |
UPDATE streaks | |
SET current_streak = ( | |
CASE | |
WHEN %(date)s - last_checkin_dt = 1 THEN current_streak + 1 | |
ELSE 1 | |
END | |
), | |
longest_streak = GREATEST(longest_streak, ( | |
CASE | |
WHEN %(date)s - last_checkin_dt = 1 THEN current_streak + 1 | |
ELSE 1 | |
END | |
)), | |
last_checkin_dt = %(date)s | |
WHERE user_id = %(user_id)s AND %(date)s > last_checkin_dt | |
RETURNING * |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment