Last active
May 25, 2018 03:43
-
-
Save chrisvaughn/7c2a5a0ca95b805321d5bd6a9b7507ca 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
-- takes a 2d array of checkins sorted by year desc. | |
-- it is assumed that the first elem in the array is the | |
-- checkins for the same year in the as_of. it will continue to | |
-- call current_streak for the year data until it finds a break in the streak | |
CREATE OR REPLACE FUNCTION current_streak_all_years(arr integer[][], as_of date) RETURNS INTEGER AS | |
$$ | |
DECLARE | |
total_streak integer := 0; | |
year_streak integer; | |
dt date; | |
start_year integer := EXTRACT(year from as_of); | |
BEGIN | |
FOR i IN array_lower(arr, 1)..array_upper(arr, 1) LOOP | |
IF i = array_lower(arr, 1) THEN | |
dt := as_of; | |
ELSE | |
dt := last_day_year(start_year - i + 1); | |
END IF; | |
year_streak := current_streak_single_year(ARRAY(SELECT unnest(arr[i:i])), dt); | |
IF year_streak = 0 THEN | |
IF total_streak > 0 THEN | |
RETURN total_streak; | |
ELSE | |
RETURN year_streak; | |
END IF; | |
ELSIF year_streak < extract(doy from dt) THEN | |
RETURN total_streak + year_streak; | |
ELSE | |
total_streak := total_streak + year_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