본문 바로가기

HackerRank

[HackerRank - SQL] The PADS

문제

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.

테이블

풀이

  • 문자열을 전처리하는 방법과 GROUP BY의 기본을 이해하고 있는지에 대해 확인하는 문제였던 것 같다.
    • GROUP BY의 기본 원리는 데이터를 그룹별로 압축한다고 알고 있다.
  • 처음엔 두 개의 쿼리를 작성하는 게 아니라 한번에 출력해야 하는 줄 알고 오랫동안 잊고 있었던 ROLLUP과 CUBE 따위의 함수들을 찾아봤었다.
  • 하지만 문제를 다시 읽어보니 두 번의 쿼리를 쓰라고 되어 있었고 그 이후론 쿼리를 작성하는 데 어렵진 않았다.
  • 마지막에 온점을 찍지 않아 헤맸다는 것만 빼면..
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;