现在有如下数据:num    s_name
                 10      xx
                 12      a
                 13      b
                 16      c
                 22      d
                 33      e
                 36      f
我想要得到一个查询结果
         10~15     3
         15~30     2
         30~40     2
请问怎么写sql

解决方案 »

  1.   

    分组有没有规律咯,如果没有规律的话就这样了
    首先给基础表做个虚拟字段:select seq,
           count(1) n
      from (
    select case when t.num>10 and t.num<=15 then 'a_10_15'
                when t.num>15 and t.num<=30 then 'a_15_30'
                when t.num>30 and t.num<=40 then 'a_30_40' else null end seq; 
      from table t
    ) group by seq
      

  2.   


    select case when num >= 10 and num < 15 then '10~15'
                when num >= 15 and num < 30 then '15~30'
                when num >= 30 and num < 40 then '30~40'
                else null
           end as ans,
           count(1) as cnt
      from t
     group by case when num >= 10 and num < 15 then '10~15'
                when num >= 15 and num < 30 then '15~30'
                when num >= 30 and num < 40 then '30~40'
                else null
           end;
      

  3.   

    引用 2 楼 的回复:SQL code
    select case when num >= 10 and num < 15 then '10~15'
    when num >= 15 and num < 30 then '15~30'
    when num >= 30 and num < 40 then '30~40'
    else null
    ……2楼的++