2014-10-10 64 views
-2

我需要拿出一個結果,顯示前3名的結果,從每個球員,以及將和數對它進行排序從每個球員前3名的結果和排序總

示例表的總和:

David = 12 Mike = 17 John = 20 Bill = 20 
David = 12 Mike = 16 John = 18 Bill = 20 
David = 11 Mike = 15 John = 16 
David = 10 Mike = 14 John = 16 
David = 10    John = 15 

結果需要顯示如下:

John = 54 
Mike = 50 
Bill = 40 
David = 35 

我已經到位排名爲所有事件(簡單):

SELECT playerName, SUM(`eventPoints`) 
FROM `eventresults` 
GROUP BY `playername` 
ORDER BY SUM(`eventPoints`) DESC 

我想做到以下幾點與PHP代碼:

  1. 創建一個表名爲top3Events在啓動
  2. 通過查詢的結果看了上面的表eventResults
  3. TRUNCATE top3Events
  4. 使用計數器並重置每個新玩家名稱
  5. INSERT INTO top3Events when counter < = 3

運行此查詢:

SELECT playerName, SUM(`eventPoints`) 
FROM `top3Events` 
GROUP BY `playername` 
ORDER BY SUM(`eventPoints`) DESC 

不知道這是去與此

+1

什麼表結構?列 ? – 4EACH 2014-10-10 14:04:10

+0

請格式化您的問題一下,之後我會刪除downvote – Miki 2014-10-10 14:05:59

+0

爲簡單起見,列是playerName,eventPoints – David 2014-10-10 14:12:47

回答

0

正確的方式我想沒有人願意解決這個。評論中有一個很好的鏈接,但我可能會使用SQL和代碼(PHP)的混合方式來處理這個問題。我的解決方案假定playerName是玩家的主鍵,有沒有非常多的玩家

我第一次執行這個查詢(最好從players表來獲得,如果有的話):

SELECT DISTINCT `playerName` 
FROM `eventResults` 

我然後遍歷該查詢結果,建立了一系列的查詢,我會UNION:要每次觀看時間進行

SELECT `sub`.`playerName`, 
    SUM(`sub`.`eventPoints`) AS `pointsSum` 
FROM (
    SELECT `playerName`, 
     `eventPoints` 
    FROM `eventResults` 
    WHERE `playerName` = '$playerName' 
    ORDER BY `eventPoints` DESC 
    LIMIT 3 
) AS `sub` 

如果計算不需要,你可以存儲產生一個彙總表並在查看時使用它。


使用在你的榜樣名稱,生成的查詢應該是這樣的:

SELECT `sub`.`playerName`, 
    SUM(`sub`.`eventPoints`) AS `pointsSum` 
FROM (
    SELECT `playerName`, 
     `eventPoints` 
    FROM `eventResults` 
    WHERE `playerName` = 'David' 
    ORDER BY `eventPoints` DESC 
    LIMIT 3 
) AS `sub` 

UNION 
SELECT `sub`.`playerName`, 
    SUM(`sub`.`eventPoints`) AS `pointsSum` 
FROM (
    SELECT `playerName`, 
     `eventPoints` 
    FROM `eventResults` 
    WHERE `playerName` = 'Mike' 
    ORDER BY `eventPoints` DESC 
    LIMIT 3 
) AS `sub` 

UNION 
SELECT `sub`.`playerName`, 
    SUM(`sub`.`eventPoints`) AS `pointsSum` 
FROM (
    SELECT `playerName`, 
     `eventPoints` 
    FROM `eventResults` 
    WHERE `playerName` = 'John' 
    ORDER BY `eventPoints` DESC 
    LIMIT 3 
) AS `sub` 

UNION 
SELECT `sub`.`playerName`, 
    SUM(`sub`.`eventPoints`) AS `pointsSum` 
FROM (
    SELECT `playerName`, 
     `eventPoints` 
    FROM `eventResults` 
    WHERE `playerName` = 'Bill' 
    ORDER BY `eventPoints` DESC 
    LIMIT 3 
) AS `sub` 

ORDER BY `pointsSum` DESC 
+0

如果這在某種程度上是正確的,那麼桑尼,你的能力必須接近通靈 – Strawberry 2014-10-13 14:54:02