문제 사이트
아래 문제는 해커랭크에서 추출해온 문제입니다. 문제의 저작권은 해커랭크에 있으며 문제를 풀어보시려면 아래 링크를 클릭해주세요 🙂
The PADS | HackerRank
Query the name and abbreviated occupation for each person in OCCUPATIONS.
www.hackerrank.com
👉문제 설명

첫번째 쿼리
- occupation테이블의 모든 이름을 알파벳 순서로 나열하고 각 직업의 첫 글자를 괄호 안에 묶어라
- name과 occupation 알파벳 순으로 정렬
두번째 쿼리
- occupation테이블에서 직업과 각 직업의 수를 오름차순으로 출력해라, 직업은 소문자로 출력
- 출력할 포맷은 'There are a total of [직업 수][직업명]s.'
- occupation_count 오름차순 정렬 후 occupation 알파벳 순으로 정렬
👉문제 풀이
총 두개의 쿼리문을 작성하는 문제이다. 문자열 관련된 함수만 알고있다면 어렵지 않게 풀 수 있는 문제인 거 같다.
👉문제 풀이 과정
1. 첫번째 쿼리
select concat(name, '(', substring(occupation, 1,1), ')')
from occupations
order by name, substring(occupation, 1,1);

- 정해진 포맷에 맞추어 출력해야 하기 때문에 문자열을 합치는 concat을 사용
- occupation의 첫 글자만 따오기 위해 substring 함수 사용
- SUBSTRING (문자열, 시작위치, 길이) : 문자열의 시작 위치부터 길이만큼 출력
2. 점수들의 합 구하기
select concat('There are a total of ', count(occupation), ' ', lower(occupation), 's.')
from occupations
group by occupation
order by count(occupation), occupation;

- occupation별 개수를 세야 했기 때문에 group by를 이용
- 정해진 포맷에 맞추기 위해 concat으로 문자열 합침
- occupation이 소문자로 출력해야하므로 LOWER()함수 사용
👉최종 답안
select concat(name, '(', substring(occupation, 1,1), ')')
from occupations
order by name, substring(occupation, 1,1);
select concat('There are a total of ', count(occupation), ' ', lower(occupation), 's.')
from occupations
group by occupation
order by count(occupation), occupation;

👉고찰
처음 문제를 보고 글이 너무 많아서 걱정했는데 생각보다 난이도가 쉬운 문제였다.
문자열 관련된 함수를 까먹었었는데 이번 문제를 풀면서 다시 복습하는 계기가 되었다.
'SQL > MySQL' 카테고리의 다른 글
[MySQL] HackerRank - Binary Tree Nodes 문제 풀이 (0) | 2024.08.31 |
---|---|
[MySQL] HackerRank - Occupations 문제 풀이 (0) | 2024.08.30 |
[MySQL] HackerRank - Contest Leaderboard 문제 풀이 (3) | 2024.08.28 |
[MySQL] HackerRank - Challenges 문제 풀이 (0) | 2024.08.16 |
[MySQL] HackerRank - Ollivander's Inventory 문제 풀이 (0) | 2024.08.15 |