在对 UserID 执行 DISTINCT 之后,我正在尝试计算有多少用户是女性和多少男性
SELECT
COUNT(IF("Gender" = 'female', 1, NULL)) as Ufemale,
COUNT(IF("Gender" = 'male', 1, NULL)) as Umale
FROM (SELECT DISTINCT UserID FROM user_stats where Year='2019' and Account='P') as UID
如果我执行
SELECT DISTINCT UserID FROM user_stats where Year='2019' and Account='P'
它返回唯一的 UserID。但是,如果我将它与计数性别部分结合起来,它会返回零。
这是值的样子
UserID | Gender
-----------------------------
2018359084885123 | male
1925823664195671 | female
2033134076795519 |
2122445674469149 | female
2315129265210413 | female
2018359084885123 | male
2122445674469149 | female
目的是展示
Ufemale | Umale
-------------------
3 | 1
最佳答案
试试这个:
表格
drop table if exists test;
create table test (userid bigint, gender char(6));
insert into test values
(2018359084885123,'male')
,(1925823664195671,'female')
,(2033134076795519, null)
,(2122445674469149,'female')
,(2315129265210413,'female')
,(2018359084885123,'male')
,(2122445674469149,'female');
查询
select
sum(case when gender = 'female' then 1 else 0 end) as ufemale,
sum(case when gender = 'male' then 1 else 0 end) as umale
from
(select distinct userid, gender from test) x
结果
ufemale umale
3 1
关于mysql - COUNT 与 IF FROM DISTINCT 值 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55884675/