1/表结构:
表数据:
SQL:
use Text
------将sum与case结合使用,可以实现分段统计。如果现在希望将上表中各种性别的人数进行统计,sql语句如下:--------------
------为什么性别为空判断不出来???????????----------------------------
----------modify---------------
select
sum(case u.stu_sex when 1 then 1 else 0 end) as 男性,
sum(case u.stu_sex when 2 then 1 else 0 end)女性,
sum(case when u.stu_sex <> 1 and u.stu_sex <> 2 then 1 else 0 end) 性别为空
from T_Stuinfo u;
结果:
----或者----
select
count(case when u.stu_sex=1 then 1 end)男性,
count(case when u.stu_sex=2 then 1 end)女,
count(case when u.stu_sex <>1 and u.stu_sex<>2 then 1 end)性别为空
from T_Stuinfo u;
结果: