2015-04-25 58 views
1

我有這個表命名結構如下獎品MySQL的計數相同的值

`id` (PRIMARY) 
`id_multiple` 
`desc` 
`winner` 

我要選擇那些沒有誰一winnerNULL)一起顯示他們,如果他們有相同的表現id_multiple有多少人贏得了這一計數,即id_multiple

因此,舉例來說,有這樣的值:

id_multiple | winner | desc 
1   | NULL | voucher 
1   | jonh | voucher 
2   | NULL | car 
2   | NULL | car 

我想顯示:

Left to win: 
1 Voucher 
2 Car 

(該desc將是相同的所有id_multiple所以它可能是不明確使用id_multiple ?)

回答

3

喜歡的東西:

SELECT id_multiple,count(id_multiple),`desc` 
FROM `yourtable` 
WHERE `winner` IS NULL 
GROUP BY `id_multiple` 
2

你可以count a case表達式:

SELECT id_multiple, COUNT(CASE WHEN winner IS NULL THEN 1 END) AS left_to_win, `desc` 
FROM  mytable 
GROUP BY id_multiple, `desc` 

甚至更​​簡單,具有sum表達,它利用的事實,true在數字環境中解釋爲1false0優勢:

SELECT id_multiple, SUM(winner IS NULL) AS left_to_win, `desc` 
FROM  mytable 
GROUP BY id_multiple, `desc`