2017-02-10 50 views
1

我想從下面的表格數據中獲得總勝率,他所玩的比賽總數以及每名球員每場勝利/比賽的比例。MySQL中每兩列的組數據計算

+---------+---------+--------+--------+--------+------+ 
| player1 | player2 | score1 | score2 | winner | year | 
+---------+---------+--------+--------+--------+------+ 
| 100000 | 100125 |  4 |  0 | 100000 | 2016 | 
| 100125 | 100126 |  4 |  0 | 100125 | 2016 | 
| 100130 | 100000 |  0 |  4 | 100000 | 2017 | 
| 100125 | 100130 |  4 |  0 | 100125 | 2017 | 
+---------+---------+--------+--------+--------+------+ 

於是問查詢應正常返回的行這樣的:

+--------+---------------+------+-------+------+ 
| player | total_matches | wins | ratio | year | 
+--------+---------------+------+-------+------+ 
| 100000 |    1 | 1 | 1  | 2016 | 
| 100000 |    1 | 1 | 1  | 2017 | 
| 100125 |    2 | 1 | 0.5 | 2016 | 
| 100125 |    1 | 1 | 1  | 2017 | 
| 100126 |    1 | 0 | 0  | 2016 | 
| 100130 |    2 | 0 | 0  | 2017 | 
+--------+---------------+------+-------+------+ 

如果我的得主,今年我可以很容易地每年奪但我不能讓TOTAL_MATCHES和比例組。 有沒有其他方法可以做到這一點? 在此先感謝。

回答

0

試試這個:

SELECT player, 
     COUNT(*) AS total_matches, 
     SUM(player = winner) AS wins, 
     SUM(player = winner)/COUNT(*) AS ratio, 
     `year` 
FROM (
    SELECT player1 AS player, winner, `year` 
    FROM mytable 

    UNION ALL 

    SELECT player2, winner, `year` 
    FROM mytable) AS t 
GROUP BY player, `year` 

查詢,以便使用UNION ALL獲取包含在單個列所有player1player2值一個表。它還使用有條件彙總以計算wins字段:SUM(player = winner)將只計算具有player = winner的那些記錄。

Demo here

+0

謝謝Giorgos。這個查詢做到了!只有一個問題,因爲表格當然包含更多的行(大約1M),因爲UNION ALL有延遲的可能性嗎? – dimoss

+0

@dimoss您可以嘗試使用您的實際數據查詢並查看它的執行情況。鑑於表結構,我想不出使用'UNION'的其他選擇。 –

+0

我會在我的實際數據中嘗試。再次感謝! – dimoss