본문 바로가기
데이터/SQL 문제풀이

HackerRank SQL - The PADS

by 찌노오 2023. 1. 3.

 

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:
    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.
  3. There are a total of [occupation_count] [occupation]s.

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 (), and then alphabetically by profession (, and ).

 

Problem

이름과 직업이 있는 테이블에서

첫 번째 쿼리는 '[이름] + ([직업의 첫 글자])' 형태로 추출하고,

두 번째 쿼리는 'There ar a total of [해당 직업의 수] [직업] s.'으로 추출하라.


Answer1

SELECT CONCAT(O.name, '(',LEFT(O.occupation,1),')') AS NAME
  FROM OCCUPATIONS O
ORDER BY NAME
;
SELECT CONCAT('There are a total of ',COUNT(O.occupation),' ',LOWER(O.occupation), 's.')
  FROM OCCUPATIONS O
GROUP BY O.occupation
ORDER BY COUNT(O.occupation), O.occupation
;

 

 

의외로 간단하게 그냥 세미콜론으로 2개의 쿼리를 이어주면 되는 문제였다.

 

 


How to solve

 

SELECT CONCAT(O.name, '(',LEFT(O.occupation,1),')')
  FROM OCCUPATIONS O
 ORDER BY NAME)
UNION ALL
SELECT CONCAT('There are a total of ', COUNT(O.occupation),' ',O.occupation, '.')
  FROM OCCUPATIONS O
GROUP BY O.occupation
ORDER BY FIELD(O.occupation, 'Doctor', 'Singer', 'Actor', 'Professor') DESC

 

굳이 UNION ALL을 할 필요가 없긴 했다. 

근데 정렬에 있어서 뭔가 꼬이는게 발생하는 것 같다.  쿼리가 2개 이상인 상황에서 UNION ALL을 하면서 각 쿼리마다 정렬을 하려고 하면 꼬이게 된다.

 

결국 굳이 UNION ALL을 써야한다면, 서브쿼리로 묶어줘야 하는데 이상한데 난 그렇게 해도 자꾸 답이 틀렸다고 나온다.

(아직 이유는 모름...)

 

 

 

 

 

 

 

반응형

'데이터 > SQL 문제풀이' 카테고리의 다른 글

HackerRank SQL - New Companies  (0) 2023.01.09
HackerRank SQL - Occupations  (1) 2023.01.06
Weather Observation Station 18  (0) 2022.11.15
HackerRank SQL - Type of Triangle  (0) 2022.11.15
HackerRank SQL - Higher Than 75 Marks  (0) 2022.11.01

댓글