SQL 스터디/HackerRank

[해커랭크] MySQL concat 구문 - The PADS

황금붕어빵 2023. 9. 11. 21:27

 


 

 

The PADS | HackerRank

Query the name and abbreviated occupation for each person in OCCUPATIONS.

www.hackerrank.com

해커랭크에서 처음 만나는 Medium 난이도의 문제였습니다.

 

크게 어려운 부분은 없긴했지만 union을 사용하다가 오래 걸렸네요..(사실 union을 사용할 필요는 없었습니다)

 

이번 해커랭크 문제는 2개의 문제가 주어졌습니다.

문제)
Generate the following two result sets:
1. 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).

2. 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.

출처 : 해커랭크

첫 번째 문제는 이름과 함께 직업의 앞글자를 괄호와 함께 출력하는 것입니다. 

 

예) AnActorName(A), ADoctorName(D) ...

select concat(name,"(",left(occupation,1),")")
from occupations
order by 1;​

CONCAT 함수를 활용해서 이름과 함께 괄호와 LEFT 함수를 활용해 직업의 앞글자를 조합하면 됩니다.

 

CONCAT 함수는 , 사이에 조합하고자 하는 문자 또는 컬럼을 기입하면 됩니다.

 

 

두 번째 문제는 아래 이미지와 같은 문구를 출력을 해야합니다.

출처 : 해커랭크

이번에도 CONCAT 구문을 활용하고 직업 앞글자가 소문자이므로 LOWER 함수를 활용해야 할 것 같습니다.

select concat("There are a total of ", cnt, " ", lower(occupation), "s.")
from (
      select occupation
           , count(*) cnt
      from occupations
      group by 1
      order by 2, 1
     ) cnt

먼저 GROUP BY 함수를 통해 각 직업을 사람이 몇 명인지 구한 후 서브쿼리 형태로 문제를 풀었습니다. 직업을 가진 사람 수가 적은 순서대로 출력하고 숫자가 같다면 직업 명 알파벳 순서대로 정렬을 해줍니다.

 

1번과 2번 문제 모두 답을 출력하기 위해서 아래와 같이 작성해줍니다.

select concat(name,"(",left(occupation,1),")") as name_pro
from occupations
order by 1;
     
select concat("There are a total of ", cnt, " ", lower(occupation), "s.")
from (
      select occupation
           , count(*) cnt
      from occupations
      group by 1
      order by 2, 1
     ) cnt

처음에는 UNION을 써야한다고 생각했는데 첫 번째 문제 쿼리 뒤에 ' ; '를 작성하면 되더군요^^