[英]How to display mysql count results from one table in different columns?
I have got one table wit users. 我有一个表机智的用户。 I want to collect girls and boys and display count numbers of them.
我想收集男孩和女孩并显示他们的数量。 I do this:
我这样做:
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)
But it shows results in one column 'boys', how I can display one row with 2 columns 'boys' and 'girls'? 但是它以单列“ boys”显示结果,我如何以两列“ boys”和“ girls”显示一行?
Just use conditional aggregation: 只需使用条件聚合:
SELECT SUM(is_male = 1) AS boys,
SUM(is_male = 0) as girls
FROM users ;
Notes: 笔记:
You can use a conditional sum 您可以使用条件和
SELECT SUM(is_male = 1) AS boys,
SUM(is_male = 0) AS girls
FROM users
or count, but then the ELSE part has to be NULL since COUNT counts all non-null values 或计数,但是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
That's conditional aggregation : 这是条件聚合:
SELECT SUM(is_male) AS boys,
SUM(is_male <> 1) AS girls
FROM users;
MySQL evaluates Boolean expressions as 1 and 0 , so no need for case expression or anything . MySQL计算布尔表达式为1和0,因此不需要大小写表达式或其他任何东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.