Skip to content

Instantly share code, notes, and snippets.

@chrisvaughn
Created May 25, 2018 03:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisvaughn/94f470dcaaf8a2f67bf71b48d2ad4c7c to your computer and use it in GitHub Desktop.
Save chrisvaughn/94f470dcaaf8a2f67bf71b48d2ad4c7c to your computer and use it in GitHub Desktop.
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