2012-10-20 83 views
3

我想向網站添加調查。一項好的調查需要報告。一些基本的報告已經完成。現在我想提上了咖啡里加點奶油...統計多個條目/統計

表樣本數據:

mysql> select * from u001; 
+----+----------+------------+-------+---------------------+ 
| id | drink | sex  | age | date    | 
+----+----------+------------+-------+---------------------+ 
| 1 | Beer  | m   | 30-39 | 2012-10-17 23:17:52 | 
| 2 | Milk  | f   | 10-19 | 2012-10-18 00:15:59 | 
| 3 | Milk  | f   | 20-29 | 2012-10-18 23:33:07 | 
| 4 | Tea  | m   | 30-39 | 2012-10-20 22:47:08 | 
| 5 | Water | f   | 20-29 | 2012-10-20 22:47:30 | 
| 6 | Milk  | m   | 30-39 | 2012-10-20 22:51:22 | 
+----+----------+------------+-------+---------------------+ 
6 rows in set (0.00 sec) 

我想計數許多女性/男性如何喜歡茶/啤酒/等結果。 ,期望的結果是這樣的:

+-------+-----+---------+ 
| drink | sex | counted | 
+-------+-----+---------+ 
| Beer | m | 1  | 
| Milk | f | 2  | 
| Tea | m | 1  | 
| Water | f | 1  | 
| Milk | m | 1  | 
+-------+-----+---------+ 

有一些人建議或解決方案? 在此先感謝。

回答

5
SELECT drink, sex, COUNT(id) counted 
FROM u001 
GROUP BY drink, sex 

SQLFiddle Demo

+0

COUNT(*)通常不是一個好主意,因爲如果有覆蓋索引,查詢可能不會使用它們。 –

+0

@Francisco,你有這方面的來源嗎? – Woutifier

+0

[COUNT(*)與COUNT(1)與COUNT(pk):哪個更好?](http://stackoverflow.com/questions/2710621/count-vs-count1-vs-countpk-which-is根據這篇文章,它沒有區別,'COUNT(*)'計數'null',而'COUNT(colName)'統計everythingexceptnull。 –

2
select drink, sex, count(id) from u001 group by drink, sex