sql - group by in ranges to include ranges without values

后端 未结 4 775
生来不讨喜
生来不讨喜 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 17:52

    You cannot like that, but if you add derived table with ranges things become possible:

    select ranges.range, count(scores.score) as [number of occurences]
      from
      (
         select 0 minRange, 9 maxRange, '0-9' range
         union all
         select 10, 19, '10-19'
         union all
         select 20, 29, '20-29'
      ) ranges
      left join scores
        on scores.score between ranges.minRange and ranges.maxRange  
     group by ranges.range
    

    Not sure about syntax of postgresql though.

    EDIT: Got the syntax right:

    select ranges."range", count(scores.score) as "number of occurences"
      from
      (
         select 0 minRange, 9 maxRange, '0-9' "range"
         union all
         select 10, 19, '10-19'
         union all
         select 20, 29, '20-29'
      ) as ranges
      left join scores
        on scores.score between ranges.minRange and ranges.maxRange  
     group by ranges.range
    

提交回复
热议问题