有一表结构如下:
字段   UserId     Age......
        1      15
        2      33
        3      70
        4      24
        5      18
现在我需要分年龄统计人数,比如
0-----20         2
21----40         2
41以上           1
请问这个sql语句该如何写?

解决方案 »

  1.   

    select count(*) where age<=.. and age>=..
      

  2.   

    select count(*) from table where age<=.. and age>=..
      

  3.   

    Select Count(*) From table Where age between 0 and 30
    so on
      

  4.   

    上面是分条写的
    如果你要一次取出来

    select count(*) where age<=20 and age>=0 union select count(*) where age<=40 and age>=21 union select count(*) where age>=41取到dataset是三条记录
      

  5.   

    不太清楚你的意思,如果效率太低可以加索引
    如果要写的太多的话,可以考虑使用SP
    如果是全部统计出来的话,在SP中使用临时表或cursor都可以的
      

  6.   

    用case语句吧select count(*)
      from  (select userid,age,case when age<=20 then 1
                                   when age>20 and age>=40 then 2
                                   else 3
                              end case as agelevel
             from table) a
    group by a.agelevel