Skip to content

Instantly share code, notes, and snippets.

@reallabs
Created April 17, 2018 21:46
Show Gist options
  • Save reallabs/11fe244a3e3bc4c9c5c8910521ab75f4 to your computer and use it in GitHub Desktop.
Save reallabs/11fe244a3e3bc4c9c5c8910521ab75f4 to your computer and use it in GitHub Desktop.
Goal Charts in SQL
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