2012-07-13 48 views
2
INSERT INTO `table` (`game_id`, `first`, `second`, `third`) 
VALUES 
    (1, 'jack', 'joe', 'pat'), 
    (2, 'jack', 'joe', 'jess'), 
    (3, 'pat', 'jess', 'jack'), 
    (4, 'pat', 'jess', 'jack'); 

這是一個統計表,每個遊戲的前三名球員。我期待拉動所有的球員,並相應地訂購他們。Mysql查詢 - 無法想出辦法做到這一點

First place - 3 points 
Second place - 2 points 
Third place - 1 point 

所以,它應該返回:

id player points 
1 jack 8 
2 pat  7 
3 jess 5 
4 joe  4 

我不能想出一個辦法,用一個查詢來做到這一點。

+0

你不應該在你的表中有字符串,你也不應該命名一個表格 – Ghost 2012-07-13 17:49:09

+0

@Ghost實際的表更復雜,只包含數字。我爲這個問題做了這個。 – domino 2012-07-13 17:51:20

+0

@Ghost爲什麼表中不應該有字符串? – octern 2012-07-13 17:53:49

回答

3
Select player, sum(points) as points from (
Select `first` as player, count(`first`)*3 as points From gameStats group by `first` 
union all 
Select `second` as player, count(`second`)*2 as points From gameStats group by `second` 
union all 
Select `third` as player, count(`third`)*1 as points From gameStats group by `third`) as tmp group by player 

這應該做到這一點。

讓我知道你是否需要任何幫助。

+0

太棒了,謝謝。 – domino 2012-07-13 18:05:17

相關問題