简体   繁体   中英

MySQL select count rows for each unique item in column

It's easiest to explain by way of an example. Lets say I have a table with 3 columns - father, their offspring and their childs sex. The result table will list the fathers number of children and the split of males and females.

This is the table:

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

Desired result:

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

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

When I use count it gives me the the total amount of children from all fathers and I'm not sure how to split the results into male and female. Any ideas?

Try:

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

Something like this:

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;

The trick is to use SUM() around a boolean variable.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM