在对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'
它返回唯一的用户ID。但是,如果我将其与性别计数部分结合使用,它将返回零。
这是值的样子
UserID | Gender
-----------------------------
2018359084885123 | male
1925823664195671 | female
2033134076795519 |
2122445674469149 | female
2315129265210413 | female
2018359084885123 | male
2122445674469149 | female
目的是展示
Ufemale | Umale
-------------------
3 | 1
答案 0 :(得分:2)
尝试一下:
表格
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
答案 1 :(得分:1)
子查询的结果中没有Gender
列:
SELECT DISTINCT UserID FROM user_stats where Year='2019' and Account='P'
您可能会想到。
您正在做的是比较两个字符串:"Gender"
和'female'
,它们显然不相等,因此:
IF("Gender" = 'female', 1, NULL)
返回NULL
,而COUNT(NULL)
返回0
。
Gender
列在哪里?
是在user_stats
表中还是像Users
这样的其他表中?
如果它位于user_stats
中,则需要这样编写查询:
select
sum(t.gender = 'female') ufemale,
sum(t.gender = 'male') umale
from (
select distinct userid, gender
from user_stats
where Year='2019' and Account='P'
) t
如果它在users
表中,则需要首先加入:
select
sum(u.gender = 'female') ufemale,
sum(u.gender = 'male') umale
from (
select distinct userid, gender
from user_stats
where Year='2019' and Account='P'
) t inner join users u
on u.userid = t.userid