2013-05-01 76 views
1

我有這個樣子
獲得最大的用戶評分與分鐘時間總結

scores 
game_id | level | score | time 
--------+-------+-------+----- 
1  | 1  | 1  | 10 
1  | 2  | 0  | 10 
1  | 3  | 1  | 20 
2  | 1  | 1  | 5 
2  | 2  | 1  | 15 
2  | 3  | 0  | 10 
3  | 1  | 0  | 10 
3  | 2  | 0  | 10 
3  | 3  | 0  | 10 

games 
game_id | user_id 
--------+-------- 
1  | 1 
2  | 1 
3  | 2 

MySQL表,我需要因此總結點和每場比賽的時間來查詢它,所以它看起來像這樣

game_id | user_id | sumPoints | sumTime 
--------+---------+-----------+-------- 
1  | 1  | 2   | 40 
2  | 1  | 2   | 30 
3  | 2  | 0   | 30 

而且比我需要得到最好的成績爲每個用戶(最好成績我的意思是其中max(sumPoints)和最小(sumTime),所以它看起來是這樣的:

game_id | user_id | sumPoints | sumTime 
--------+---------+-----------+-------- 
2  | 1  | 2   | 30 
3  | 2  | 0   | 30 

那就是最終結果。我可以做點和時間總結的部分,但我不知道我怎麼能得到每個用戶的分數。 我想知道,我怎麼能通過SQL查詢做到這一點? 在此先感謝

+0

我想你的意思是'2 | 1 | 2 | 30'不'1 | 1 | 2 | 30' – 2013-05-02 00:28:18

回答

1

以下查詢將爲您提供部分結果。

SELECT a.game_ID, 
     b.user_id, 
     SUM(a.Score) sumPoint, 
     SUM(a.time) sumTime 
FROM scores a 
     INNER JOIN games b 
      ON a.game_ID = b.game_ID 
GROUP BY a.game_ID, b.user_id 

輸出

╔═════════╦═════════╦══════════╦═════════╗ 
║ GAME_ID ║ USER_ID ║ SUMPOINT ║ SUMTIME ║ 
╠═════════╬═════════╬══════════╬═════════╣ 
║  1 ║  1 ║  2 ║  40 ║ 
║  2 ║  1 ║  2 ║  30 ║ 
║  3 ║  2 ║  0 ║  30 ║ 
╚═════════╩═════════╩══════════╩═════════╝ 

由於MySQL不支持Windows的功能就像任何其他的RDBMS,這可能是凌亂出示你想要的結果。

SELECT a.* 
FROM 
     (
      SELECT a.game_ID, 
        b.user_id, 
        SUM(a.Score) sumPoint, 
        SUM(a.time) sumTime 
      FROM scores a 
        INNER JOIN games b 
         ON a.game_ID = b.game_ID 
      GROUP BY a.game_ID, b.user_id 
     ) a 
     INNER JOIN 
     (
      SELECT user_ID, 
        MIN(sumTime) sumTime 
      FROM 
        (
         SELECT a.game_ID, 
           b.user_id, 
           SUM(a.Score) sumPoint, 
           SUM(a.time) sumTime 
         FROM scores a 
           INNER JOIN games b 
            ON a.game_ID = b.game_ID 
         GROUP BY a.game_ID, b.user_id 
        ) s 
      GROUP BY user_ID 
     ) b ON a.user_id = b.user_id AND 
       a.sumTime = b.sumTime 

輸出

╔═════════╦═════════╦══════════╦═════════╗ 
║ GAME_ID ║ USER_ID ║ SUMPOINT ║ SUMTIME ║ 
╠═════════╬═════════╬══════════╬═════════╣ 
║  2 ║  1 ║  2 ║  30 ║ 
║  3 ║  2 ║  0 ║  30 ║ 
╚═════════╩═════════╩══════════╩═════════╝ 
0

JW的回答基本上是我的一樣。我只是認爲,如此早地引導用戶似乎會使事情不必要地複雜化。如何...

SELECT x.* 
    , u.user_id 
    FROM 
    (SELECT game_id 
      , SUM(score) ttl_score 
      , SUM(time) ttl_time 
     FROM scores 
     GROUP 
      BY game_id 
    ) x 
    JOIN 
    (SELECT ttl_score 
      , MIN(ttl_time) min_ttl_time 
     FROM 
      (SELECT game_id 
        , SUM(score) ttl_score 
        , SUM(time) ttl_time 
       FROM scores 
       GROUP 
        BY game_id 
      ) a 
     GROUP 
      BY ttl_score 
    ) y 
    ON y.ttl_score = x.ttl_score 
    AND y.min_ttl_time = x.ttl_time 
    JOIN games g 
    ON g.game_id = x.game_id;