본문 바로가기

코딩일기

SQL 코드카타 149 - The PADS

https://www.hackerrank.com/challenges/the-pads/problem?isFullScreen=true

 

The PADS | HackerRank

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

www.hackerrank.com

 

 

Column Type
Name String
Occupation String

 

OCCUPATIONS 테이블:

  • Name : 이름
  • Occupation : 직업

다음 두 결과 집합을 생성하세요:

  1. OCCUPATIONS 테이블에서 모든 이름을 알파벳순으로 정렬한 목록을 조회하세요. 각 이름 뒤에는 해당 직업의 첫 글자를 괄호로 묶어 표시하세요. 예: AnActorName(A), ADoctorName(D), AProfessorName(P), ASingerName(S).
  2. OCCUPATIONS 테이블에서 각 직업의 발생 횟수를 조회하세요. 발생 횟수를 오름차순으로 정렬하고, 다음 형식으로 출력하세요:
There are a total of [occupation_count] [occupation]s.

 

여기서 [occupation_count]는 OCCUPATIONS 테이블에서 해당 직업이 나타난 횟수이고, [occupation]은 소문자로 된 직업 이름입니다. 여러 직업이 동일한 [occupation_count]를 가지는 경우, 알파벳순으로 정렬하세요.

 

select
    name,
    Occupation
from OCCUPATIONS
order by name

 

먼저 이름에 대해서 오름차순으로 정렬한다.

 

select concat(Name, ' (', substring(Occupation, 1, 1),')')
from
(select
    name,
    Occupation
from OCCUPATIONS
order by name) a

 

정렬된 쿼리에서 이름과 직업의 첫글자를 괄호를 합쳐서 출력한다.

 

select
    Occupation,
    count(Occupation)
from OCCUPATIONS
group by Occupation
order by count(Occupation), Occupation

 

새로운 쿼리를 작성하여 직업의 수를 기준으로 오름차순 정렬한다. 같을 경우 직업의 이름을 기준으로 오름차순 정렬한다.

 

select
    concat('There are a total of ', c, ' ', Occupation ,'s.' )
from
(select
    Occupation,
    count(Occupation) c
from OCCUPATIONS
group by Occupation
order by count(Occupation), Occupation) a

 

concat을 이용해서 조건에 맞게 출력해준다.

 

select concat(Name, '(', LEFT(Occupation, 1),')')
from
(select
    name,
    Occupation
from OCCUPATIONS
order by name) a;

select
    concat('There are a total of ', c, ' ', lower(Occupation), 's.' )
from
(select
    Occupation,
    count(Occupation) c
from OCCUPATIONS
group by Occupation
order by count(Occupation), Occupation) a

 

union으로 결합해야하는줄알고 시간이 꽤 걸렸다...