문제
Generate the following two result sets:
- Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses). For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S).
- Query the number of ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format:
There are a total of [occupation_count] [occupation]s.
where [occupation_count] is the number of occurrences of an occupation in OCCUPATIONS and [occupation] is the lowercase occupation name. If more than one Occupation has the same [occupation_count], they should be ordered alphabetically.
Note: There will be at least two entries in the table for each type of occupation.
Occupation will only contain one of the following values: Doctor, Professor, Singer or Actor.
다음 두 개의 결과 집합을 생성하세요:
- OCCUPATIONS 테이블에 있는 모든 이름을 알파벳 순으로 정렬한 후, 각 이름 뒤에 해당 직업의 첫 글자를 괄호로 묶어서 출력하세요.
예: AnActorName(A), ADoctorName(D), AProfessorName(P), ASingerName(S) - OCCUPATIONS 테이블에서 각 직업이 등장한 횟수를 조회하세요.
이 결과는 등장 횟수를 기준으로 오름차순 정렬하고, 다음과 같은 형식으로 출력되어야 합니다:
There are a total of [occupation_count] [occupation]s.
SELECT
CONCAT(NAME, '(', SUBSTRING(O.Occupation, 1, 1), ')')
FROM
OCCUPATIONS O
ORDER BY
NAME ASC;
WITH TEMP AS(
SELECT
COUNT(*) AS C, Occupation
FROM
OCCUPATIONS
GROUP BY
Occupation
)
SELECT
CONCAT('There are a total of ', CAST(C AS CHAR), ' ', lower(Occupation), 's.')
FROM
TEMP
ORDER BY
C ASC, Occupation ASC;
정답 쿼리다. 기술적으로 어렵지 않지만 어떻게 풀어야 하는지 감이 오지 않았다. WITH 쓰고 파티션 쓰고 별 짓 다해봤다. UNION을 써보려 했는데 UNION은 컬럼 수와 컬럼 타입이 동일해야 쓴다는 예상밖의 지식을 얻었다. 문제를 푸는 방법은 간단하다. 그냥 SELECT을 두번 쓰면 된다.
아래는 결과물
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)
There are a total of 3 doctors.
There are a total of 4 actors.
'MYSQL > HakerRank_Medium' 카테고리의 다른 글
Weather Observation Station 20(중앙값 구하기) (0) | 2025.04.16 |
---|---|
Weather Observation Station 19, 유클리드 거리 구하기 (0) | 2025.04.16 |
Weather Observation Station 18 (0) | 2025.04.15 |
New Companies (0) | 2025.04.15 |
Binary Tree Nodes (0) | 2025.04.14 |