Skip to content

Instantly share code, notes, and snippets.

@spencerroan
Created June 20, 2016 22:48
Show Gist options
  • Save spencerroan/60d4c8f5df999098c008ac34f95fcd2e to your computer and use it in GitHub Desktop.
Save spencerroan/60d4c8f5df999098c008ac34f95fcd2e to your computer and use it in GitHub Desktop.
We can make this file beautiful and searchable if this error is corrected: It looks like row 3 should actually have 1 column, instead of 3 in line 2.
with current_goals as (
select g.user_id, g.id, 'eat_move_sleep' as goal_type
from eat_move_sleep_goals g
where now() between start_date and end_date
union
select g.user_id, g.id, 'weight_loss' as goal_type
from weight_loss_goals g
where now() between start_date and end_date
union
select g.user_id, g.id, 'stress_reduction' as goal_type
from stress_reduction_goals g
where now() between start_date and end_date
),
user_goals as (
select cg.*, ht.occurred_on
from current_goals cg left join hydrated_temp ht on cg.user_id = ht.user_id
where company_id = 12 or company_id = 4
),
week_goals as (
select goal_type, count(*) as week from
(
select distinct goal_type, user_id
from user_goals
where occurred_on between now() - interval '7 days' and now()
) foo
group by goal_type
),
month_goals as (
select goal_type, count(*) as month from
(
select distinct goal_type, user_id
from user_goals
where occurred_on between now() - interval '28 days' and now()
) foo
group by goal_type
),
goal_counts as (
select goal_type, count(goal_type) from current_goals group by goal_type
)
select gc.*, mg.month, wg.week from goal_counts gc
left join week_goals wg on gc.goal_type = wg.goal_type
left join month_goals mg on gc.goal_type = mg.goal_type;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment