clear markdown compare help donate or buy diddy dollings comments/suggestions/bugs a leap of faith? bible365
clear markdown donate comments/suggestions/bugs a leap of faith? bible365 diddy dollings
By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0. 756676 fiddles created (13637 in the last week).

CREATE TABLE T(amount INT, index INT); INSERT INTO T VALUES (55, 1),(88, 5),(45, 6),(86, 7),(87, 10), (88, 11),(57, 16),(58, 17),(59, 20),(60, 21);
10 rows affected
 hidden batch(es)


SELECT generate_series(0, 14, 4) Serie;
serie
0
4
8
12
 hidden batch(es)


CREATE OR REPLACE FUNCTION GroupIntervals(low int, high int, step int) RETURNS TABLE (amount int, interv int) AS $$ BEGIN RETURN QUERY WITH CTS AS ( SELECT generate_series(low, high, step) Serie ) SELECT COALESCE(SUM(T.amount),0)::int AS amount, CTS.Serie as interv FROM CTS LEFT JOIN T ON index >= CTS.Serie AND index < CTS.Serie + step GROUP BY CTS.Serie ORDER BY CTS.Serie; END; $$ LANGUAGE plpgsql;
 hidden batch(es)


SELECT * FROM GroupIntervals(0, 14, 4);
amount interv
55 0
219 4
175 8
0 12
 hidden batch(es)


SELECT * FROM GroupIntervals(5, 14, 5);
amount interv
219 5
175 10
 hidden batch(es)


WITH CTS AS ( SELECT generate_series(0, 14, 4) Serie ) SELECT COALESCE(SUM(amount),0) AS amount, CTS.Serie FROM CTS LEFT JOIN T ON index >= CTS.Serie AND index < CTS.Serie + 4 GROUP BY CTS.Serie ORDER BY CTS.Serie;
amount serie
55 0
219 4
175 8
0 12
 hidden batch(es)