Suppose a scenario similar to this question. I want to get the following results:
score range | number of occurrences
-------------------------------------
0
Try this query (also on SQL Fiddle):
WITH ranges AS (
SELECT (ten*10)::text||'-'||(ten*10+9)::text AS range,
ten*10 AS r_min, ten*10+9 AS r_max
FROM generate_series(0,9) AS t(ten))
SELECT r.range, count(s.*)
FROM ranges r
LEFT JOIN scores s ON s.score BETWEEN r.r_min AND r.r_max
GROUP BY r.range
ORDER BY r.range;
EDIT:
You can easily adjust the range by changing parameters to generate_series()
. It is possible to use the following construct to make sure ranges
will always cover your scores:
SELECT (ten*10)::text||'-'||(ten*10+9)::text AS range,
ten*10 AS r_min, ten*10+9 AS r_max
FROM generate_series(0,(SELECT max(score)/10 FROM scores)) AS t(ten))
for the ranges
CTE.