Skip to content

Instantly share code, notes, and snippets.

@neilmiddleton
Created January 20, 2012 15:03
Show Gist options
  • Save neilmiddleton/1647768 to your computer and use it in GitHub Desktop.
Save neilmiddleton/1647768 to your computer and use it in GitHub Desktop.
Lead with Postgres
select months.month,
COALESCE(users.count,0) AS count,
lead(count,1) over (order by months) as prev_month,
(count - (lead(count,1) over (order by months)) ) as delta
from
(
SELECT generate_series(
date_trunc('year', min(created_at)),
now(),
'1 month'::interval
)::date as month
from users
) months
INNER JOIN
(
SELECT count(*) as count
, date_trunc('month', created_at)::date as month
FROM users
GROUP BY date_trunc('month', created_at)
) users on users.month = months.month
ORDER BY month
month count prev_mondelta
"2009-04-01" 4 27 -23
"2009-05-01" 27 21 6
"2009-06-01" 21 28 -7
"2009-07-01" 28 30 -2
"2009-08-01" 30 20 10
"2009-09-01" 20 27 -7
"2009-10-01" 27 19 8
"2009-11-01" 19 25 -6
"2009-12-01" 25 33 -8
"2010-01-01" 33 17 16
"2010-02-01" 17 30 -13
"2010-03-01" 30 23 7
"2010-04-01" 23 26 -3
"2010-05-01" 26 23 3
"2010-06-01" 23 28 -5
"2010-07-01" 28 34 -6
"2010-08-01" 34 19 15
"2010-09-01" 19 28 -9
"2010-10-01" 28 26 2
"2010-11-01" 26 19 7
"2010-12-01" 19 25 -6
"2011-01-01" 25 26 -1
"2011-02-01" 26 27 -1
"2011-03-01" 27 28 -1
"2011-04-01" 28 24 4
"2011-05-01" 24 25 -1
"2011-06-01" 25 20 5
"2011-07-01" 20 18 2
"2011-08-01" 18 25 -7
"2011-09-01" 25 23 2
"2011-10-01" 23 25 -2
"2011-11-01" 25 22 3
"2011-12-01" 22 17 5
"2012-01-01" 17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment