SQL/HackerRank

[HackerRank/SQL] The PADS

류진주 2021. 11. 6. 16:07

https://www.hackerrank.com/challenges/the-pads/problem

 

The PADS | HackerRank

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

www.hackerrank.com

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.

 

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:

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.

 

Explanation

The results of the first query are formatted to the problem description's specifications.
The results of the second query are ascendingly ordered first by number of names corresponding to each profession (2<=2<=3<=3), and then alphabetically by profession (doctor<=singer, and actor<=professor).

 


[풀이]

MySQL을 이용하여 해결하였다.

 

첫번째 쿼리의 결과는 이름에 직업의 첫번째 알파벳을 이어붙인 결과를 이름 순으로 정렬하여 나타낸 것이다.

그러므로 문자열을 이어붙이는 CONCAT()과 문자열의 Substring을 가져올 수 있는 SUBSTR()을 이용하여 SELECT절을 완성한다.

그 다음 이름 순으로 정렬해야하므로 ORDER BY절에 NAME을 작성한다.

첫번째 쿼리를 모두 작성하고 나면 ;(세미콜론)을 붙여 쿼리를 끝낸다.

 

두번째 쿼리의 결과는 특정 직업을 가진 사람의 수를 세고, 그 값과 직업을 소문자로 변환하여 이어붙인 문자열을 조회해야 한다. 값을 조회하는 순서는 occupation_count가 작은 순서이고 만약 그 값이 같아면 occupation의 알파벳 순으로 조회한다.

그러므로 GROUP BY절에서 직업 별로 OCCUPATIONS 테이블을 그룹화하고, SELECT절에서 COUNT(*)로 해당 직업을 가진 사람 수를 센다. 

출력 형식은 There are a total of [occupation_count] [occupation]s. 이므로 CONCAT()을 이용하여 출력 형식에 맞게 만든다. 직업을 소문자로 변경하기 위해 LOWER()를 사용한다.

값을 정렬하기 위해 ORDER BY절에 COUNT(*), OCCUPATION;을 작성한다.

 

[코드]

SELECT CONCAT(NAME, '(', SUBSTR(OCCUPATION, 1, 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;