You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HackerRank挑战The PADS:SQL查询输出不符合预期怎么办?

问题描述

我正在解决HackerRank的The PADS挑战,期望输出如下:

Ashely(P)
Christeen(P)
Jane(A)
Jenny(D)
Julia(A)
Ketty(P)
Maria(A)
Meera(S)
Priya(S)
Samantha(D)
There are a total of 2 doctors.
There are a total of 2 singers.
There are a total of 3 actors.
There are a total of 3 professors.

我编写的SQL查询语句为:

select concat(name,'(',left(occupation,1),')') 
from occupations
order by name;
select concat('There are a total of ', count(*),' ', occupation,'s') from occupations
group by occupation
order by count(occupation);

但每次执行后得到的输出如下:

Aamina(D)
Ashley(P)
Belvet(P)
Britney(P)
Christeen(S)
Eve(A)
Jane(S)
Jennifer(A)
Jenny(S)
Julia(D)
Ketty(A)
Kristeen(S)
Maria(P)
Meera(P)
Naomi(P)
Priya(D)
Priyanka(P)
Samantha(A)
concat('There are a total of ', count(*),' ', occupation,'s')
There are a total of 3 Doctors
There are a total of 4 Actors
There are a total of 4 Singers
There are a total of 7 Professors

请问我的查询哪里出错了?

问题分析与修正方案

你的查询存在三个核心问题,修正后即可匹配期望输出:

  1. 职业名称格式不符
    期望输出里的职业是全小写(如doctors)且末尾带句点.,你的查询输出的是首字母大写(如Doctors),也缺少句点。

  2. 第二查询出现多余表头行
    输出里的concat('There are a total of ', count(*),' ', occupation,'s')是查询的列名,部分SQL环境会默认输出列名,需要调整拼接逻辑补全格式,确保结果直接输出内容而非列名。

  3. 排序逻辑不完整
    第二部分统计结果需要先按总数升序排列,总数相同时按职业名称的字母顺序升序排列,你的查询只按总数排序,缺少职业名称的排序条件。

修正后的SQL语句:

-- 生成姓名+职业缩写的结果行
SELECT CONCAT(name, '(', LEFT(occupation, 1), ')')
FROM occupations
ORDER BY name;

-- 生成统计结果行,修正格式与排序
SELECT CONCAT('There are a total of ', COUNT(*), ' ', LOWER(occupation), 's.')
FROM occupations
GROUP BY occupation
ORDER BY COUNT(*), occupation;

修正细节说明:

  • 使用LOWER(occupation)将职业名称转为全小写,匹配期望格式。
  • 在拼接字符串末尾添加句点.,对齐输出要求。
  • 第二查询的排序条件改为ORDER BY COUNT(*), occupation,先按统计数量升序,数量相同则按职业名称字母顺序升序。
  • 拼接后的列无需额外别名,HackerRank的环境会直接输出结果内容,不会显示列名。

内容的提问来源于stack exchange,提问作者NiMa03

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 13:17:31