日期:2014-05-18  浏览次数:20469 次

能否用一条select 语句统计出这个表
表A

id name sex age
1 张三 男 30
2 李四 男 25
3 小梅 女 18
4 大明 男 40
5 大时 女 30



怎样用一条语句同时查出 男性的个数与年龄大于20岁的个数?

------解决方案--------------------
SQL code
select sex
      ,sum(case when sex='男' then 1 else 0 end) 男性个数
       ,sum(case when age>20 then 1 else 0 end) [大于20岁的个数]
from 表A
group by sex

------解决方案--------------------
SQL code

select 男人数=sum(case sex when '男' then 1 else 0 end),年龄大于20的人数=sum(case  when age>=20 then 1 else 0 end) from tb

男人数         年龄大于20的人数
----------- -----------
3           4

(1 行受影响)