具有 IF FROM DISTINCT 值的计数 MySQL

COUNT with IF FROM DISTINCT values MySQL

在对 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'

它returns 唯一的 UserID。但是,如果我将它与计数性别部分结合起来,它 returns 零。

值如下所示

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

示例:https://rextester.com/JLQ19855

子查询的结果中没有 Gender 列:

SELECT DISTINCT UserID FROM user_stats where Year='2019' and Account='P'

如你所想。
您正在做的是比较 2 个字符串:"Gender"'female',它们显然不相等,因此:

IF("Gender" = 'female', 1, NULL)

returns NULLCOUNT(NULL) returns 0.
Gender 列在哪里?
它是在 user_stats table 中还是在另一个 table 中,例如 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 table 中,那么您首先需要一个连接:

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