반응형

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:
where [occupation_count] is the number of occurrences of an occupation in OCCUPATIONS and [occupation] is the lowercaseoccupation name. If more than one Occupation has the same [occupation_count], they should be ordered alphabetically. There are a total of [occupation_count] [occupation]s.
Note: There will be at least two entries in the table for each type of occupation.
Input Format
The OCCUPATIONS table is described as follows:

Occupation will only contain one of the following values: Doctor, Professor, Singer or Actor.
Sample Input
An OCCUPATIONS table that contains the following records:

MySQL에서는 문자열을 연결할 때 `||` 연산자를 사용할 수 없습니다. 대신 `CONCAT()` 함수를 사용해야 합니다. 이 포스팅에서는 `OCCUPATIONS`라는 테이블을 기반으로 다음 두 가지 작업을 실습해봅니다:
1. 이름 뒤에 직업의 첫 글자를 괄호로 붙이기 (예: `Meera(S)`)
2. 각 직업별 인원 수 출력하기 (예: `There are a total of 3 singers.`)
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;
- CONCAT(): 문자열을 이어붙이는 MySQL 함수
- LEFT(OCCUPATION, 1): 직업의 첫 글자 추출
- ORDER BY NAME: 이름 기준 정렬
- COUNT(*): 각 직업별 인원 수 계산
- LOWER(): 직업명을 소문자로
- 's.': 직업명 뒤에 ‘s.’ 붙여서 복수형 처리
- ORDER BY COUNT(*): 인원 수 기준 오름차순 정렬
- 인원 수가 같을 경우, ORDER BY OCCUPATION 으로 사전순 정렬
반응형
'Computer Science > SQL' 카테고리의 다른 글
SQL | HackerRank 이진 트리 노드 유형(Root, Inner, Leaf) 구분하는 쿼리 (0) | 2025.06.16 |
---|---|
SQL | HackerRank MAX(CASE WHEN…)을 활용한 피벗(Pivot) 쿼리 (0) | 2025.06.15 |
SQL | HackerRank 정규표현식으로 도시 찾기 – DISTINCT와 REGEXP 활용 (0) | 2025.06.13 |
SQL | HackerRank 가장 짧고 긴 도시 이름 찾기 – 문자열 길이 기반 SQL 정렬과 조건 추출 (1) | 2025.06.12 |
SQL | HackerRank 삼각형 분류하기: 조건문 CASE를 활용한 다중 조건 처리 (0) | 2025.06.11 |