2
我希望將我的數據按年齡和性別:像這樣的樣本數據:MySQL的分組
Age: 1
Male: 2
Female: 3
Age 1 Total: 5
Age: 2
Male: 6
Female: 3
Age 2 Total: 9
我怎麼能集團根據年齡和數據統計在那個時代所有的男性和女性從MySQL數據庫?
我希望將我的數據按年齡和性別:像這樣的樣本數據:MySQL的分組
Age: 1
Male: 2
Female: 3
Age 1 Total: 5
Age: 2
Male: 6
Female: 3
Age 2 Total: 9
我怎麼能集團根據年齡和數據統計在那個時代所有的男性和女性從MySQL數據庫?
Select age, gender, Count(*) cnt
From your_table
Group By age, gender
將讓你
Age Gender cnt
1 Male 2
1 Female 3
2 Male 6
2 Female 9
您應該能夠總結計數每個年齡在PHP之後。
SELECT
age,
SUM(CASE WHEN gender = 'male' THEN 1 ELSE 0 END) males,
SUM(CASE WHEN gender ='female' THEN 1 ELSE 0 END) females,
COUNT(*) total
FROM yourtable
GROUP BY age
+1這是正確的答案。雖然因爲OP使用MySQL,所以我會縮短到'選擇年齡,總和(性別='男性')男性,總和(性別='女性')女性,按年齡計算(*)來自一個羣體的總數「 – 2010-05-07 08:20:47
非常感謝,我的堆棧中增加了一項新的mysql技術。 – text 2010-05-07 09:00:37
謝謝邁克爾,這是一個非常優雅的改變! – ceteras 2010-05-07 09:23:19