我的问题如下:
黑客的总得分是他们在所有挑战中的最大得分之和。编写一个查询,以打印黑客的
hacker_id、姓名和总分。 如果多个黑客获得相同的总分,则通过升序hacker_id对结果进行排序。 将所有得分为0的黑客排除在你的结果之外。 这两个表如下:
表:骇客
========================================
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; 我的输出是错误的,尽管这个输出满足了所有的顺序规则&如果需要的话,0得分者的忽略。我很困惑这个错误是什么。救命啊!
发布于 2017-07-25 17:14:17
黑客的总得分是的之和,他们的最大得分是所有挑战的总和。
首先,您需要找到黑客的最大得分,对于每一个挑战:
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_id、name和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发布于 2017-07-25 16:58:32
类似于:
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子句为每个黑客得到一个新的总数。然后将订单添加到。最后,HAVING会过滤掉任何得分为零的人。
我没有你的数据集来测试,但希望这是足够接近,它将帮助你前进的道路!
https://stackoverflow.com/questions/45309407
复制相似问题