Prøv denne forespørgsel (også på 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:
Du kan nemt justere området ved at ændre parametre til generate_series()
. Det er muligt at bruge følgende konstruktion for at sikre ranges
vil altid dække dine 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 ranges
CTE.