sql - group by in ranges to include ranges without values

后端 未结 4 765
生来不讨喜
生来不讨喜 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:48

    select r.range as [score range], count(*) as [number of occurences]
    from 
        (
        select ' 0- 9' as range, 9 as endrange
        union all select '10-19',19
        union all select '20-29',29
        union all select '30-39',39
        union all select '40-49',49
        union all select '50-59',59
        union all select '60-69',69
        union all select '70-79',79
        union all select '80-89',89
        union all select '90-99',99
        ) as r
    left join scores s on 
        r.endrange = case 
        when s.score > 90 then 99
        when s.score > 80 then 89
        when s.score > 70 then 79
        when s.score > 60 then 69
        when s.score > 50 then 59
        when s.score > 40 then 49
        when s.score > 30 then 39
        when s.score > 20 then 29
        when s.score > 10 then 19
        when s.score > 0 then 9
        end
    group by r.range
    

提交回复
热议问题