다음 2개의 결과 집합을 생성하시오.
1. 직업의 모든 이름을 알파벳 순으로 정렬한 목록을 조회하고, 바로 뒤에 각 직업의 첫 글자를 괄호로 묶는다(즉, 괄호 안에 묶음). 예를 들어, Actor(A), Doctor(D), Professor(P) 및 Singer(S)
2. 각 직종의 발생 횟수를 조회하여 오름차순으로 정렬하고, 다음과 같은 형식으로 출력한다:
There are a total of [occupation_count] [occupation]s.
여기서 [occupation_count]는 직업에서 직업이 발생한 횟수이고 [occupation]은 소문자 직업명이다. 둘 이상의 직업이 동일한 [occupation_count]을 가지면 알파벳 순서로 정렬해야 한다.
with t1 as(
select concat(name,'(',left(upper(occupation),1),')') as oc
from occupations
order by oc),
t2 as(
select concat('There are a total of',space(1),count(*),space(1),lower(occupation),'s.')
from occupations
group by occupation
order by count(*),occupation
)
select * from (
select * from t1
union
select * from t2) AS t
order by t.oc;
select와 select를 바로 union 하면 개별 쿼리의 order by가 제대로 작동하지 않는다. 서브 쿼리를 사용하면, DBMS가 개별 쿼리를 정렬한 이후 결합하는 형태로 이해하기 때문에 정렬된 결과를 확인할 수 있다. 하지만, 해당 쿼리는 불필요하게 복잡하다고 생각해서 문제 해결 이후 다른 사용자들의 풀이를 확인했다.
select concat(name,'(',left(upper(occupation),1),')') as oc
from occupations
order by oc;
select concat('There are a total of',space(1),count(*),space(1),lower(occupation),'s.')
from occupations
group by occupation
order by count(*),occupation;
최근 문제를 해결한 다수의 사용자들이 단순히 쿼리를 2개 나열해서 문제를 풀었다. 각 쿼리의 결과를 개별적으로 제시해도 column이 하나이기 때문에 정답인지 모르겠지만, 문제가 안풀릴 때는 다른 관점으로도 접근해보도록 하자.
The PADS | HackerRank
Query the name and abbreviated occupation for each person in OCCUPATIONS.
www.hackerrank.com
'코딩 테스트 > SQL' 카테고리의 다른 글
| [MySQL] 프로그래머스 - 특정 조건을 만족하는 물고기별 수와 최대 길이 구하기 (0) | 2024.06.25 |
|---|---|
| [MySQL] - Placements (0) | 2024.02.08 |
| [MySQL] HackerRank - Weather Observation Station 20 (2) | 2024.01.16 |
| [MySQL] HackerRank - The Report (2) | 2024.01.14 |
| [MySQL] HackerRank - Weather Observation Station 5 (2) | 2024.01.14 |