Created
May 25, 2018 03:43
-
-
Save chrisvaughn/94f470dcaaf8a2f67bf71b48d2ad4c7c to your computer and use it in GitHub Desktop.
This file contains hidden or 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 OR REPLACE FUNCTION current_streak_single_year(arr integer[], as_of date) RETURNS INTEGER AS | |
$$ | |
DECLARE | |
total_streak integer := 0; | |
month_streak integer; | |
dt date; | |
BEGIN | |
FOR i IN REVERSE month_index(as_of)..1 LOOP | |
IF date_part('month', as_of) = i THEN | |
dt := as_of; | |
ELSE | |
dt := last_day_month(make_date(date_part('year', as_of)::integer, i, 1)); | |
END IF; | |
month_streak := current_streak_for_month(arr[i], dt); | |
IF month_streak = 0 THEN | |
IF total_streak > 0 THEN | |
RETURN total_streak; | |
ELSE | |
RETURN month_streak; | |
END IF; | |
ELSIF month_streak < day_of_month(dt) THEN | |
RETURN total_streak + month_streak; | |
ELSE | |
total_streak := total_streak + month_streak; | |
END IF; | |
END LOOP; | |
RETURN total_streak; | |
END; | |
$$ LANGUAGE 'plpgsql'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment