-
-
Save reallabs/11fe244a3e3bc4c9c5c8910521ab75f4 to your computer and use it in GitHub Desktop.
Goal Charts in SQL
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
WITH dates as ( | |
SELECT ds, row_number() OVER () as rnum | |
FROM generate_series( | |
date_trunc('month', now())::timestamp AT TIME ZONE 'PST', | |
date_trunc('month', now() + INTERVAL '1 month')::timestamp AT TIME ZONE 'PST', | |
'24 hours') | |
as ds | |
) | |
SELECT ds, goal, | |
CASE WHEN LAG(metric) OVER (ORDER BY ds) = metric | |
THEN NULL | |
ELSE metric | |
END as metric | |
FROM ( | |
SELECT a.ds, | |
START_METRIC + ((a.rnum-1) * (END_GOAL-START_METRIC) / (DAYS_IN_MONTH-1)) as goal, | |
COUNT(DISTINCT b.id) as metric | |
FROM dates a | |
LEFT OUTER JOIN TABLE_NAME b | |
ON date_trunc('day', a.ds) >= date_trunc('day', b.created_at AT TIME ZONE 'PST') | |
AND date_part('month', b.created_at AT TIME ZONE 'PST') = MONTH_OF_YEAR | |
GROUP BY 1,2 | |
) a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment