SQL case when 查询性别统计总数,为什么性别为空的数量是0

搬砖码农SmallNNN 2016-01-29 04:27:48
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;
结果:


...全文
655 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
引用 3 楼 roy_88 的回复:
[quote=引用 2 楼 u014180504 的回复:] [quote=引用 1 楼 roy_88 的回复:] 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 is null then 1 else 0 end) 性别为空 from T_Stuinfo u;
确实能够查出来了,能解释下原因吗?[/quote] NULL不属于任何值,NULL 值表示列的数据值未知或不可用,只能用IS NULL或IS NOT NULL查,或转值 ISNULL(NULL,0)=0这样表达 或配置 SET ANSI_NULLS OFF[/quote] 好的,我是一名菜鸟,谢谢你的回答
  • 打赏
  • 举报
回复
引用 4 楼 KanzakiOrange 的回复:
你这个语句原因在于 Null 值是不确定值 1 <> null 返回的是 unknow ,既不是 true 也不是 false ,所以你获取不到。 判断null 只能使用 is null 和 is not null 进行判断
十分感谢您的解析,谢谢您
Ginnnnnnnn 2016-01-29
  • 打赏
  • 举报
回复
你这个语句原因在于 Null 值是不确定值 1 <> null 返回的是 unknow ,既不是 true 也不是 false ,所以你获取不到。 判断null 只能使用 is null 和 is not null 进行判断
中国风 2016-01-29
  • 打赏
  • 举报
回复
引用 2 楼 u014180504 的回复:
[quote=引用 1 楼 roy_88 的回复:] 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 is null then 1 else 0 end) 性别为空 from T_Stuinfo u;
确实能够查出来了,能解释下原因吗?[/quote] NULL不属于任何值,NULL 值表示列的数据值未知或不可用,只能用IS NULL或IS NOT NULL查,或转值 ISNULL(NULL,0)=0这样表达 或配置 SET ANSI_NULLS OFF
  • 打赏
  • 举报
回复
引用 1 楼 roy_88 的回复:
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 is null then 1 else 0 end) 性别为空 from T_Stuinfo u;
确实能够查出来了,能解释下原因吗?
中国风 2016-01-29
  • 打赏
  • 举报
回复
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 is null then 1 else 0 end) 性别为空 from T_Stuinfo u;

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧