admin

以最少的时间总和获得最高的用户分数

sql

我有看起来像这样的 MySql 表

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

我需要查询它,以便它总结每场比赛的积分和时间,所以它看起来像这样

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

然后我需要为每个用户获得最好的分数(最好的分数我的意思是 max(sumPoints) 和 min(sumTime),所以它看起来像这样:

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

这就是最终的结果。我可以做点和时间相加的部分,但我不知道如何获得每个用户的最高分数。我想知道,我怎样才能通过 SQL 查询做到这一点?提前致谢


阅读 169

收藏
2021-07-01

共1个答案

admin

下面的这个查询会给你部分结果。

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不像任何其他 RDBMS 一样支持 Windows 函数,因此这可能会产生您想要的结果。

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 ║
╚═════════╩═════════╩══════════╩═════════╝
2021-07-01