Skip to content

Instantly share code, notes, and snippets.

@tomredsky
Created October 24, 2018 13:02
Show Gist options
  • Save tomredsky/f06924c377d8fc3b20efd1266c5f5b88 to your computer and use it in GitHub Desktop.
Save tomredsky/f06924c377d8fc3b20efd1266c5f5b88 to your computer and use it in GitHub Desktop.
Create series on invoice totals by month
-- Collect min and max date range
WITH range_values AS (
SELECT date_trunc('month', min(dat)) as minval,
date_trunc('month', max(dat)) as maxval
from IV),
-- Generate date range in monthly intervals
months as (
SELECT generate_series(minval, maxval, '1 month'::interval) as month
from range_values
)
-- How to join against IV when all I have is a month?
select mr.month, sum(tot) from months mr
join iv on mr.month=iv.dat
where dat between (mr.month - interval '1 month') and mr.month
group by 1;
==== Outputs this (which is wrong ) ====
month | sum
------------------------+-----------
1987-05-01 00:00:00+00 | 0.00
1987-07-01 00:00:00+00 | 0.00
1987-10-01 00:00:00+00 | 2542.50
1988-03-01 00:00:00+00 | 487.40
1988-06-01 00:00:00+00 | 100.00
1989-02-01 00:00:00+00 | -60.00
1990-03-01 00:00:00+00 | 60.00
1990-05-01 00:00:00+00 | 120.00
1990-06-01 00:00:00+00 | 105.00
1990-08-01 00:00:00+00 | 123.50
1990-10-01 00:00:00+00 | 328.00
1990-11-01 00:00:00+00 | 147.70
1991-02-01 00:00:00+00 | 181.34
1991-03-01 00:00:00+00 | 220.45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment