SQL case when 查询性别统计总数,为什么性别为空的数量是0
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;
结果:


表数据:

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;
结果:

...全文
相关推荐
SQL查询语句实用大全(适合SQL的初学者以及经常写SQL的人)
空值查询**空值查询**用于检查列是否为空或不为空。使用`IS NULL`或`IS NOT NULL`实现。
SQL中的case…when…还能这么用(计算好评率、计算出有条件的字段的数量)
**场景2:性别与成绩统计**教师可能希望在一个查询中得到班级男女学生数量以及男女及格人数。
SQL集合函数中case when then 使用技巧
在标题提到的“SQL集合函数中`CASE WHEN THEN` 使用技巧”中,主要讨论了如何利用`CASE WHEN THEN` 结合`COUNT()`函数在聚合查询中统计特定条件的数据。
sql查询班级男女
例如,count(sc.StuId)函数用于计算每个班级的学生总数,sum(case when sc.StuSex='男' then 1 else 0 end)用于计算班级中男性学生的数量,而sum(case
一个用来统计相同姓名人数的SQl语句
1 ELSE 0 END)` 分别用于统计男性和女性的数量。


