I have a table containing an amount column and an index column.
I wish to build a single query, which sums up the amount for the given interval ranges for every resulting interval from given start index to end index – i.e. the 'interval range' slices the data according index column. For these groups, sum over amount is built.
Is this possible and how?
SELECT sum(amount) from mytable
WHERE index between <startindex> and <endindex>
GROUP BY ...
Example:
amount | index
55 1
88 5
45 6
86 7
87 10
88 11
57 16
58 17
59 20
60 21
A query with interval range 5, start index 5 and endindex 14 should result in two return values:
88+45+86 => 219
87+88 => 175
A query with interval range 4, start index 0 and endindex 15 should result in four return values:
55 => 55
88+45+86 => 219
87+88 => 175
-- => 0
Thanks for any help!
Best Answer
You can take advantage of Postgres function generate_series().
The example below uses a series from 0 to 14 with an interval of 4.
You can use a user defined function that allows you to use parameters
dbfiddle here
Update
As Evan Carrol has pointed out on him comments you can avoid use CTE and change function language from plpgsql to plain SQL.
dbfiddle here