stemie
stemie

Reputation: 779

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?

Upvotes: 1

Views: 233

Answers (3)

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58271

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

Upvotes: 2

Daniel Sparing
Daniel Sparing

Reputation: 2173

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;

Upvotes: 1

Hackerman
Hackerman

Reputation: 12295

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;

Upvotes: 1

Related Questions