[해커랭크] THE PADS

멋쟁이펭귄맨·2021년 9월 16일
0

문제링크

문제

  1. OCCUPATIONS의 모든 names을 불러오기, 각 직업의 첫번째 알파벳을 ()안에 넣어 표시할 것. 예시) ActorName(A), DocterName(D)

  2. 각 직업의 숫자를 아래의 양식에 따라 print할 것 (직업명의 오름차순에 따라)
    There are a total of [occupation_count] [occupation]s.

  3. Note: There will be at least two entries in the table for each type of occupation.


INPUT FORMAT

TABLE NAME : OCCUPATIONS

columntype
NAMESTRING
OCCUPATIONSTRING


SAMPLE INPUT



SAMPLE OUTPUT

Ashely(P)
Christeen(P)
Jane(A)
Jenny(D)
Julia(A)
Ketty(P)
Maria(A)
Meera(S)
Priya(S)
Samantha(D)
There are a total of 2 doctors.
There are a total of 2 singers.
There are a total of 3 actors.
There are a total of 3 professors.


문제풀이


일단 필요한 기능을 찾아보았다.

1) CONCAT, CONCAT_WS 를 활용한 STRING 연결하기
<-> 비교 : ORACLE은 || 를 활용하여 STRING을 연결할 수 있다.

CONCAT

SELECT CONCAT(str1, str2 ...)

  • 문자열을 나열하여 값을 합침
  • NULL이 들어가면 반환값은 무조건 null이다.

CONCAT_WS

SELECT CONCAT_WS(separator, str1, str2 ...)

  • 문자열을 나열하여 값을 합치며, separator값을 활용가능.
  • NULL이 들어가가면 NULL을 제외한 str값들을 합쳐서 반환한다.

2) SUBSTR을 활용하여 직업 COLUMN의 첫째 글자 추출하기

3) GROUP BY와 ORDER BY 를 활용한 정렬

4) COUNT 함수를 활용한 직업별 숫자 세기

5) LOWER 함수를 활용한 소문자 반환

6) SET sql_mode = ''; 코드 통하여 ONLY_FULL_GROUP_BY 해제

참고 링크



쿼리

SELECT CONCAT(NAME, '(',SUBSTR(OCCUPATION, 1,1) ,')')
FROM OCCUPATIONS
ORDER BY NAME;

SET sql_mode = '';
SELECT CONCAT('There are a total of ',COUNT(NAME),' ',OCCUPATION,'s.') 
FROM OCCUPATIONS
GROUP BY OCCUPATION 
ORDER BY COUNT(NAME), OCCUPATION;

이 코드 상태에서 계속 에러가 떠서 뭐가 문제인지 계속 찾아보았다.

알고 보니 문제에서 직업명을 소문자로 표기하라는 조건이 있었다...

SELECT CONCAT(NAME, '(',SUBSTR(OCCUPATION, 1,1) ,')')
FROM OCCUPATIONS
ORDER BY NAME;

SET sql_mode = '';
SELECT CONCAT('There are a total of ',COUNT(NAME),' ',LOWER(OCCUPATION),'s.') 
FROM OCCUPATIONS
GROUP BY OCCUPATION 
ORDER BY COUNT(NAME), OCCUPATION;

OUTPUT

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. 
There are a total of 4 singers. 
There are a total of 7 professors.

정답! 처음으로 맞춰본 해커랭크 medium 문제다.

profile
안녕하세요

0개의 댓글