2016-12-28 90 views
2

下面這個查詢:如何修改這個mysql查詢來顯示勝率?

SELECT member, count(*) Wins 
FROM (SELECT player2_name as member from results 
WHERE player1_id = 2 AND player1_result = 'W' AND community_id = 16 
UNION ALL SELECT player1_name FROM results WHERE player2_id = 2 
AND player2_result = 'W' AND community_id = 16) AS T 
group by member ORDER BY Wins DESC 

產生的結果,如:

+---------+-----------+ 
| member | Wins | 
+---------+-----------+ 
| Player 1|  4  | 
| Player 2|  3  | 
| Player 3|  3  | 
+---------+-------------+ 

爲了使數據更加有用(如每個玩家可能都起到了不同數量的遊戲)我想說明的額外的列'勝利百分比'。

- >這是基於每個玩家玩過/贏的遊戲數量。 - 如果輸出%是不可能直接在MySQL則小數就可以了,即0.76

我如何修改我現有的查詢產生如下的輸出:

+---------+-----------+---------------+---------+ | member | Wins | Games Played | Win % | +---------+-----------+---------------+---------+ | Player 1| 4 | 8 | 0.50 | | Player 2| 3 | 3 | 1.00 | | Player 3| 3 | 5 | 0.60 | +---------+-----------+---------------+---------+

我希望只是在添加一些東西沿着線:

SELECT GamesPlayed FROM (SELECT player1_name as member from results 
WHERE player1_id = 2 AND community_id = 16 
UNION ALL SELECT player2_name FROM results WHERE player2_id = 2 
AND community_id = 16) AS GP 

,然後在1號線:

SELECT member, count(*) Wins, round(sum(wins/GamesPlayed(1),2) WinPercentage 

但是,這是一個非常粗糙的希望我猜怎麼看它的工作。

最新的測試數據: enter image description here

+0

你還能改變你的數據庫模式?每個「遊戲」(每個參與者一個)有兩個記錄的表格會更容易處理。 – Mr47

+0

我可以做,但我不想...... – RDowns

回答

2

像這樣的事情?

更新查詢

SELECT 
    T.member 
    , count(*) Wins 
    , total.gamesPlayed 
    , count(*)/total.gamesPlayed as winPercentage 
FROM 
    (
     SELECT 
      player2_name as member 
     from results 
     WHERE 
      player1_id = 2 
      AND player1_result = 'W' 
      AND community_id = 16 
     UNION ALL 
     SELECT 
      player1_name 
     FROM results 
      WHERE player2_id = 2 
      AND player2_result = 'W' 
      AND community_id = 16 
    ) AS T 
    , (
      select 
       u.member 
       , sum(u.gamesPlayed) as gamesPlayed 
      from 
       (
        select 
         player2_name as member 
         , count(*) gamesPlayed 
        from results 
        where 
         player1_id = 2 
         AND community_id = 16 
        group by player2_name 
        union 
        select 
         player1_name as member 
         , count(*) gamesPlayed 
        from results 
        where 
         player2_id = 2 
         AND community_id = 16 
        group by player2_name 
       ) as u /* union of two */ 
      group by member 
    ) as total 
where 
    T.member = total.member 
group by T.member 
ORDER BY Wins DESC 
+0

謝謝李,它只是彈出一個錯誤在第31行..#1064 - 你的SQL語法錯誤;檢查對應於你的MySQL服務器版本的手冊正確的語法使用近「分別COUNT(*)gamesPlayed從結果 其中 」第31行 – RDowns

+0

對不起,我忘了兩個逗號,在第31行和40(前'計數(*)'在子查詢'u'中)。由於我沒有你的表格,我不能運行查詢,所以可能會有其他小的語法錯誤,但希望我的查詢可以給你一些想法如何找到總數,你可以從那裏接受查詢。 – leeyuiwah

+0

幾乎在那裏,但它給錯誤的玩家錯誤的數據 - 我會上傳一個截圖來解釋。 在屏幕截圖中,對Sultan玩的遊戲應該是4,而對G玩的遊戲應該是1 ... – RDowns