首页 > 试题广场 >

Mysql中表student_table(id,name,b

[单选题]
Mysql中表student_table(id,name,birth,sex),id字段值可能重复,分别查询男生、女生的不重复id总数,如下SQL正确的是()?
  • select
    sum(distinct case when sex='男' then 1 else null end) as man_ids,
    sum(distinct case when sex='女' then 1 else null end) as women_ids
    from student_table;
  • select
    count(distinct case when sex='男' then id else null end) as man_ids,
    count(distinct case when sex='女' then id else null end) as women_ids
    from student_table;
  • select
    count(distinct case when sex='男' then 1 else null end) as man_ids,
    count(distinct case when sex='女' then 1 else null end) as women_ids
    from student_table;
  • select
    count(case when sex='男' then distinct id else null end) as man_ids,
    count(case when sex='女' then distinct id else null end) as women_ids
    from student_table;
选项A如下. 
select
sum(distinct case when sex='男' then 1 else null end) as man_ids,
sum(distinct case when sex='女' then 1 else null end) as women_ids
from student_table; 
在select后面的指定列,如case when sex='男' then 1 else null end,则所有行的结果都变成了1,再进行distinct,就只有1行为1的数据,最后通过sum,得到答案为1。而选项B中是对id执行distinct操作,得到的是去重的id列表,再count,便是不重复的id数。
发表于 2022-02-24 22:04:59 回复(0)
先用case when 判断男女,取出id号,再对id号去重,然后再使用count进行id号统计数量
发表于 2022-02-18 12:18:32 回复(0)
为什么A不对啊?sum也会计算null值吗

发表于 2022-01-30 21:45:59 回复(10)
没转过来,是因为执行顺序原因,先执行case when then,然后再执行distinct ,这样之后再sum或者count,结果自然为1
发表于 2022-10-27 19:16:19 回复(0)
对于A选项,使用sum+distinct的话,因为男的都是1,女的也都是1,那么distinct之后只有 1,1 再sum之后肯定还是1,1;但是倘若sum不加distinct,那么达不到去重的效果,id字段重复的性别会连续被计数。
如果使用count,D选项本身错误,C选项,distinct之后,因为then之后都是1,1,那么也是输出1,1。
B选项,then之后是id,再distinct之后会把重复的id删除,而且再count就是所要的结果了
发表于 2022-06-13 10:23:55 回复(0)
count里面写id代表对id去重计数    都为1去重后结果都为1
发表于 2023-11-08 11:47:58 回复(0)
链接:https://www.nowcoder.com/questionTerminal/1f195cc4c09f4d629f8e0b458714515b
来源:牛客网
select sum(distinct case when sex='男' then 1 else null end) as man_ids, sum(distinct case when sex='女' then 1 else null end) as women_ids from student_table;
男        女
1           1
null       1
1            null
1            1
去重后只会剩下2条记录
男        女
1           1
null       null
sum求和后也就只会是1了


发表于 2023-03-06 09:41:45 回复(0)
大意了没去重

发表于 2022-07-13 19:42:54 回复(0)
C为什么不对?
发表于 2022-07-11 17:09:30 回复(0)