我有一个表机智用户。 我想收集女孩和男孩,并显示他们的计数。 我这样做:
SELECT COUNT(`is_male`) AS 'boys' FROM `users` WHERE `is_male` = 1 UNION (SELECT COUNT(`is_male`) AS 'girls' FROM `users` WHERE `is_male` = 0)
但是它显示了一个列'男孩'的结果,我如何显示一行有2列“男孩”和“女孩”?
答案 0 :(得分:3)
只需使用条件聚合:
SELECT SUM(is_male = 1) AS boys,
SUM(is_male = 0) as girls
FROM users ;
注意:
答案 1 :(得分:0)
您可以使用条件和
SELECT SUM(is_male = 1) AS boys,
SUM(is_male = 0) AS girls
FROM users
或count,但是ELSE部分必须为NULL,因为COUNT计算所有非空值
SELECT count(case when is_male = 1 then 1 else null end) AS boys,
count(case when is_male = 0 then 1 else null end) AS girls
FROM users
答案 2 :(得分:0)
这是条件聚合:
SELECT SUM(is_male) AS boys,
SUM(is_male <> 1) AS girls
FROM users;
MySQL将布尔表达式计算为1和0,因此不需要大小写表达式或任何内容。