MySQL为列中的每个唯一项选择计数行

时间:2014-02-28 13:59:42

标签: mysql inner-join

通过一个例子来解释是最容易的。让我们说我有一个有三列的桌子 - 父亲,他们的后代和他们的孩子的性别。结果表将列出父亲的子女数量以及男性和女性的分配情况。

这是表格:

Father   Child    Sex
-----------------------
alpha    name1    m
alpha    name2    f
alpha    name3    m
alpha    name4    f
alpha    name5    f
beta     name6    m
beta     name7    m
charlie  name8    f
charlie  name9    m

期望的结果:

Father   num   m    f
-----------------------
alpha    5     2    3
beta     2     2    0
charlie  2     1    1

num = number of children
m = male, f = female

当我使用伯爵时,它给了我所有父亲的孩子总数,我不知道如何将结果分成男性和女性。 有什么想法吗?

3 个答案:

答案 0 :(得分:2)

尝试:

SELECT
    Father,
    COUNT(child) AS total_child, 
    SUM(IF(Sex = 'm', 1, 0)) AS total_m,
    SUM(IF(Sex = 'f', 1, 0)) AS total_f
FROM
    table_name
GROUP BY
    Father

答案 1 :(得分:1)

这样的事情:

select distinc t.Father, 
(select count(1) from table t1 where t1.Father = t.Father) as num,
(select count(1) from table t1 where t1.Father = t.Father and Sex = 'm') as m,
(select count(1) from table t1 where t1.Father = t.Father and Sex = 'f') as f
from table t;

答案 2 :(得分:1)

诀窍是在布尔变量周围使用SUM()

SELECT Father, COUNT(Child) as num, SUM(Sex='m') as m, SUM(Sex='f') as f
FROM table
GROUP BY Father;