In SQL, how can you “group by” in ranges?

前端 未结 15 2396
粉色の甜心
粉色の甜心 2020-11-22 15:38

Suppose I have a table with a numeric column (lets call it \"score\").

I\'d like to generate a table of counts, that shows how many times scores appeared in each ran

15条回答
  •  余生分开走
    2020-11-22 16:25

    select t.range as score, count(*) as Count 
    from (
          select UserId,
             case when isnull(score ,0) >= 0 and isnull(score ,0)< 5 then '0-5'
                    when isnull(score ,0) >= 5 and isnull(score ,0)< 10 then '5-10'
                    when isnull(score ,0) >= 10 and isnull(score ,0)< 15 then '10-15'
                    when isnull(score ,0) >= 15 and isnull(score ,0)< 20 then '15-20'               
             else ' 20+' end as range
             ,case when isnull(score ,0) >= 0 and isnull(score ,0)< 5 then 1
                    when isnull(score ,0) >= 5 and isnull(score ,0)< 10 then 2
                    when isnull(score ,0) >= 10 and isnull(score ,0)< 15 then 3
                    when isnull(score ,0) >= 15 and isnull(score ,0)< 20 then 4             
             else 5  end as pd
         from score table
         ) t
    
    group by t.range,pd order by pd
    

提交回复
热议问题