MYSQL中的输出错误

时间:2017-07-25 16:52:48

标签: mysql

我有一个问题如下:

  

黑客的总分是所有挑战的最高分数之和。编写查询以打印按降序排列的黑客的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个得分手。我对这个错误是什么感到很困惑。有人请帮忙!!!

2 个答案:

答案 0 :(得分: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是过滤任何零分的人。

我没有将您的数据集进行测试,但希望这足够接近它将帮助您一路走来!

答案 1 :(得分: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_idnametotal 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