使用MySQL返回1个表中的男性数量和女性数量

时间:2015-02-12 03:14:13

标签: mysql mysql-workbench

我需要使用MySQL返回1个表中的男性数量和女性数量。我创建了一个返回带有男性和女性行的表的查询,但我的列没有被填充。其结果= 0;

这是我的查询。我拿到了桌子,但它没有填充

SELECT COUNT(gender) AS 'Female', COUNT(gender) AS 'Male'
FROM customers
WHERE gender = 'female' AND 'male';

任何建议,

3 个答案:

答案 0 :(得分:4)

这应该有效:

SELECT
  SUM(IF(gender = 'female', 1, 0)) AS 'Female',
  SUM(IF(gender = 'male', 1, 0)) AS 'Male'
FROM customers

根据性别是女性(或男性),IF会得到1或0的值,然后您只需将这些0和1总和得到总数。

答案 1 :(得分:0)

您也可以执行CASE声明:

SELECT
    SUM(CASE WHEN gender = 'female' THEN 1 ELSE 0 END) AS 'Female',
    SUM(CASE WHEN gender = 'male' THEN 1 ELSE 0 END) AS 'Male'
FROM customers

答案 2 :(得分:0)

由于MySQL将true1false0等同,您可以使用更短的版本:

SELECT
  SUM(gender = 'female') AS `Female`,
  SUM(gender = 'male')   AS `Male`
FROM customers

SQL FIDDLE