有没有一种方法可以简化此基本联接查询?

时间:2020-08-06 16:21:57

标签: mysql sql

我对SQL还是很陌生,我一直在线进行一些练习以提高查询技能。

我正在尝试解决此问题:https://www.hackerrank.com/challenges/contest-leaderboard/problem

我能够使用下面的代码解决它,但是我想知道是否有任何方法可以简化它/使其更有效?

SELECT
    id,
    name,
    total_score
FROM(
SELECT
    id,
    name,
    SUM(sscore) as total_score
FROM(
SELECT
    id,
    name,
    challenge_id,
    MAX(score) as sscore
FROM(
SELECT
    hacker_id as id,
    name,
    submission_id,
    challenge_id,
    score
FROM
    Hackers
INNER JOIN
    Submissions s USING(hacker_id)
ORDER BY
    hacker_id,
    challenge_id)a
GROUP BY id, name, challenge_id)b
GROUP BY id, name
ORDER BY total_score DESC, id ASC)c
WHERE total_score > 0;

2 个答案:

答案 0 :(得分:0)

这是我尝试过的,提交成功。

SELECT b.hacker_id, b.name , c.total_score from (
SELECT a.hacker_id as hid, SUM(a.max_score) as total_score from (
        SELECT hacker_id, max(score) as max_score from Submissions group by hacker_id, challenge_id
    ) as a group by a.hacker_id
) as c INNER JOIN Hackers b
ON b.hacker_id = c.hid
WHERE c.total_score > 0
ORDER BY c.total_score DESC,
b.hacker_id ASC

答案 1 :(得分:0)

您只需要一个联接,而不是两个或三个。要控制0个值,可以使用HAVING子句。

enter image description here

SELECT a.hacker_id,a.name, SUM(a.mscore) from (
        SELECT h.hacker_id,h.name, max(score) as mscore from Submissions s inner join hackers h on h.hacker_id=s.hacker_id group by h.hacker_id, challenge_id,h.name
    ) as a group by a.hacker_id,a.name
HAVING SUM(a.mscore) > 0
ORDER BY 3 DESC,
1 ASC