现在有这样的数据
dptid  qty   age
0101    1    22
0101    5    23
0101    3    25,
age为年龄字段,我想取出 20岁以下有多少,20<=age<23有多少,23<=age<26有多少,26>age有多少,
即上面的数据显示为
dptid qty1 qty2 qty3 qty4
0101   0    6    3    0
这样的数据,求指导

解决方案 »

  1.   

    select dptid,
    sum(case when age<20 then 1 else 0 end) as qty1,
    sum(case when age>=20 and age<23 then 1 else 0 end) as qty2,
    sum(case when age>=23 and age<26 then 1 else 0 end) as qty3,
    sum(case when age>=26 then 1 else 0 end) as qty4
    from tb
      

  2.   

    少了一句group byselect dptid,
    sum(case when age<20 then 1 else 0 end) as qty1,
    sum(case when age>=20 and age<23 then 1 else 0 end) as qty2,
    sum(case when age>=23 and age<26 then 1 else 0 end) as qty3,
    sum(case when age>=26 then 1 else 0 end) as qty4
    from tb 
    group by dptid