显示零值的行

时间:2014-05-06 13:39:49

标签: php mysql sql

我有以下查询来显示基于性别的人数:

 SELECT gender, 
    count( * ) AS count
 FROM persons
    CROSS JOIN (SELECT count( * ) AS total 
                FROM persons) x
 GROUP BY 1
 ORDER BY gender DESC

结果:

Male    | 5

如何还显示零值的行,例如:

Male    | 5
Female  | 0

2 个答案:

答案 0 :(得分:3)

找出男性/女性人数的简单解决方案

SELECT  
    SUM(gender='Male' ) AS `Male`,
    SUM(gender='Female' ) AS `Female`
 FROM persons
 GROUP BY gender

这将产生类似

的输出
Male  Female
5       0

或者为了显示行,你可以使用union

SELECT 'Male' AS gender,COUNT(*) `count` FROM persons WHERE gender='Male'
UNION
SELECT 'Female' AS gender,COUNT(*) `count` FROM persons WHERE gender='Female'

这将输出为

gender count

Male   5
Female 0

答案 1 :(得分:0)

好吧,如果你要找的东西实际上和性别一样快,你可以随时UNION ALL

SELECT [Gender], COUNT(*) [Total] FROM [Persons] WHERE [Gender] = 'Male' GROUP BY [Gender]

UNION ALL

SELECT [Gender], COUNT(*) [Total] FROM [Persons] WHERE [Gender] = 'Female' GROUP BY [Gender]