2017-07-25 21 views
0

我有一個問題如下:輸出錯在MYSQL

黑客的總得分是他們的最高分數的所有挑戰的總和。撰寫查詢以打印hacker_id,名稱和按降序排列的黑客總分。
如果不止一個黑客獲得相同的總分,則按升序排序hacker_id
從結果中排除總分爲0的所有黑客。
2.表中給出如下:

表:黑客

======================================== 
hacker_id: Integer (ID of the hacker) 
name: String (Name of the hacker) 
======================================== 

表:提交

=================================================== 
submission_id: Integer (ID of the submission) 
hacker_id:  Integer (ID of the hacker) 
challenge_id: Integer (ID of the challenge) 
score:   Integer (score of the submission) 
=================================================== 

MySQL查詢我已經書面如下: -

select 
    a.hacker_id, 
    a.name, 
    a.total 
from(
    select 
     h.hacker_id, 
     h.name, 
     sum(case when s.hacker_id=h.hacker_id then s.score else 0 end) as total 
    from 
     hackers h, 
     submissions s 
    group by 
     h.hacker_id, 
     h.name 
) as a 
where 
    a.total>0 
order by 
    a.total desc, 
    a.hacker_id asc; 

我得到的輸出錯誤這雖然那輸出滿足要求爲了& ommission的0得分的所有規則。對於錯誤是什麼我很困惑。有人請幫助!

+0

首先,使用正確的連接。你不需要這兩張表的笛卡爾積。 – Eric

回答

0

黑客的總得分是所有的挑戰總和他們最大分數。

首先,你需要找到的最大比分黑客,對於每一個挑戰:

SELECT hacker_id 
    , challenge_id 
    , MAX(score) AS max_score 
    FROM Submissions 
GROUP BY hacker_id 
     , challenge_id 

然後,你需要總結,對於每個黑客:

SELECT hacker_id 
    , SUM(max_score) AS total_score 
    FROM (SELECT hacker_id 
       , challenge_id 
       , MAX(score) AS max_score 
      FROM Submissions 
      GROUP BY hacker_id 
       , challenge_id 
     ) ms 
GROUP BY hacker_id 

最後在應用其餘:

排除所有黑客與total score爲0從你的結果。

打印hacker_idname,並total score

由降score排序,然後按升序hacker_id

SELECT hacker_id 
    , (SELECT name 
      FROM Hackers h 
      WHERE h.hacker_id = ms.hacker_id 
     ) AS name 
    , SUM(max_score) AS total_score 
    FROM (SELECT hacker_id 
       , challenge_id 
       , MAX(score) AS max_score 
      FROM Submissions 
      GROUP BY hacker_id 
       , challenge_id 
     ) ms 
GROUP BY hacker_id 
HAVING SUM(max_score) <> 0 
ORDER BY total_score DESC 
     , hacker_id 
+0

優秀的解釋! – Priya

1

喜歡的東西:

select h.hacker_id, h.name, sum(s.score) as total 
from hackers h 
join submissions s using (hacker_id) 
group by h.hacker_id 
order by sum(s.score) desc, h.name 
having sum(s.score) > 0 

的基本思路是,開始與我們一起黑客和意見表一起,再總結成績,並使用group by子句以獲得每個黑客新的總。然後添加按順序。然後最後HAVING是過濾掉零分的任何人。

我沒有你的數據集來測試,但希望這足夠接近,它會幫助你一路!

+0

您錯過了「最大」部分:*「黑客的總分數是其最大**分數的總和」*。你總結了多次提交相同的挑戰,這是不對的。 ---通過'group by',您可以將'h.name'作爲結果列。 ---二級排序不是「h.name」。 ---從句的順序是錯誤的(在'順序完成後'不能'有')。 – Andreas

+0

啊,沒有設法從原始問題版本解析黑客可以多次提交,好點 –