【问题标题】:Wrong output in MYSQLMYSQL 输出错误
【发布时间】:2017-12-31 17:46:24
【问题描述】:

我有一个问题如下:

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

【问题讨论】:

  • 首先,使用正确的连接。您不需要两张表的笛卡尔积。

标签: mysql


【解决方案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 过滤掉任何得分为零的人。

我没有您要测试的数据集,但希望这足够接近,它将在此过程中对您有所帮助!

【讨论】:

  • 您缺少“最高”部分:“黑客的总分是他们最高分的总和”。您正在汇总同一挑战的多次提交,这是不对的。 --- 有了group by,您可以将h.name 作为结果列。 --- 二级排序不是h.name。 --- 子句顺序错误(having 后面不能有order by)。
  • 啊,没能从黑客可以多次提交的原始问题版本中解析出来,好地方
【解决方案2】:

黑客的总分是他们在所有挑战中的最高分的总和

首先,您需要找到黑客在每个挑战中的最高得分:

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

【讨论】:

    猜你喜欢
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    相关资源
    最近更新 更多