sql - group by in ranges to include ranges without values

后端 未结 4 757
生来不讨喜
生来不讨喜 2021-02-13 17:45

Suppose a scenario similar to this question. I want to get the following results:

score range  | number of occurrences
-------------------------------------
   0         


        
4条回答
  •  清酒与你
    2021-02-13 18:04

    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.

提交回复
热议问题