mariadb 如何使用mysql查询在总分相同的情况下增加排名?

pkbketx9  于 2022-11-08  发布在  Mysql
关注(0)|答案(1)|浏览(127)

这是我的疑问:

SELECT
    `users`.`id` AS userID,
    `user_tests`.`id`,
    `users`.`profilePic`,
    `users`.`firstName`,
    `user_tests`.`userId`,
    `user_tests`.`isFirstAttempt`,
    `user_tests`.`total_marks`,
    FIND_IN_SET(
        `user_tests`.`total_marks`,
        (
        SELECT
            GROUP_CONCAT(
                DISTINCT `user_tests`.`total_marks`
            ORDER BY
                CAST(
                    `user_tests`.`total_marks` AS DECIMAL(5, 3)
                )
            DESC
            )
        FROM
            `user_tests`
        WHERE
            `user_tests`.`testSeriesId` = '856' AND `user_tests`.`isFirstAttempt` = '1'
    )
    ) AS rank,
FROM
    `user_tests`
LEFT JOIN `users` ON `users`.id = `user_tests`.`userId`
WHERE
    `user_tests`.`isFirstAttempt` = '1' AND `user_tests`.`testSeriesId` = '856'
ORDER BY
    CAST(
        `user_tests`.`total_marks` AS DECIMAL(5, 3)
    )
DESC
    ,
    `submissionTimeInMinutes` ASC,
    `rank` ASC;

输出量:
this is the image
预期值:
Here is the expected output image
我使用的是MariaDB 5.5.68,我尝试过使用变量来递增,但它显示的是当前行号,而不是1,2,3,4,5 ...数字。
有人能帮忙吗?谢谢。

xqnpmsa8

xqnpmsa81#

您似乎不需要左连接,因为没有遗漏任何用户名。一个简单的子查询将按total_mark为您提供排名,但我不确定您是在计算用户数还是其他内容。CTE将使您避免重复某些逻辑,甚至可能更快。我不知道您是否有此选择。

SELECT
    u.id AS userID, t.id, u.profilePic, u.firstName,
    t.userId, t.isFirstAttempt, t.total_marks,
    (
        SELECT count(distinct userId) from FROM user_tests t2
        WHERE     t.isFirstAttempt = 1 AND t.testSeriesId = 856
              AND t.total_marks < t2.total_marks
    ) as num_tests
FROM user_tests t inner join users u ON u.id = t.userId
WHERE t.isFirstAttempt = 1 AND t.testSeriesId = 856
ORDER BY total_marks desc, submissionTimeInMinutes, num_tests desc

相关问题