2014-02-28 149 views
1

通過示例的方式來解釋這是最容易的。可以說我有一張3列的表 - 父親,他們的後代和他們的孩子的性別。結果表格將列出父親的子女人數和男性和女性的分數。MySQL爲列中每個唯一項目選擇計數行

這是表:

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 

當我使用指望它給了我所有父親的孩子們的總量的,我不知道如何將結果分成男性和女性。 任何想法?

+0

顯示您所使用的SQL語句返回錯誤計數 – AgRizzo

回答

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 
+0

優秀的答案...我只是編輯COOUNT;) – Hackerman

+0

得益於正確的錯字@RobertRozas ...但還沒有測試。 –

+1

Grijesh和我回去的路上。他是你的SQL人員。我爲了好玩而製作了[this](http://sqlfiddle.com/#!2/9be0c/3)。 – Drewness

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; 
1

的技巧是使用SUM()圍繞一個布爾變量。

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