sql - GROUP BY next months over N years -
i need aggregate amounts grouped "horizon" 12 next months on 5 year:
assuming 2015-08-15
sum amount 0 12 next months (from 2015-08-16 2016-08-15) sum amount 12 24 next months (from 2016-08-16 2017-08-15) sum amount 24 36 next months ... sum amount 36 48 next months sum amount 48 60 next months
here fiddled dataset example:
+----+------------+--------+ | id | date | amount | +----+------------+--------+ | 1 | 2015-09-01 | 10 | | 2 | 2015-10-01 | 10 | | 3 | 2016-10-01 | 10 | | 4 | 2017-06-01 | 10 | | 5 | 2018-06-01 | 10 | | 6 | 2019-05-01 | 10 | | 7 | 2019-04-01 | 10 | | 8 | 2020-04-01 | 10 | +----+------------+--------+
here expected result:
+---------+--------+ | horizon | amount | +---------+--------+ | 1 | 20 | | 2 | 20 | | 3 | 10 | | 4 | 20 | | 5 | 10 | +---------+--------+
how can these 12 next months grouped "horizons" ?
i tagged postgresql i'm using orm it's find idea. (by way don't have access date formatting functions)
i split 12 months time frame , group this:
select floor( (extract(epoch date) - extract(epoch now())) / extract(epoch interval '12 month') ) + 1 "horizon", sum(amount) "amount" dataset group horizon order horizon;
inspired by: postgresql sql group time interval arbitrary accuracy (down milli seconds)
Comments
Post a Comment