The PADS 문제 바로 가기 

 

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

문제정리

쿼리 두개 작성

1. 이름을 알파벳 순으로 정렬하고 이름 옆에 직업의 맨 앞 글자만 괄호쳐서 나타내는 쿼리 작성

2. 직업의 수와 직업이름을 소문자로 바꿔 결과값을 

"There are a total of [occupation_count] [occupation]s." 이 문장으로 나타내는 쿼리 작성 

   직업수로 내림차순 정렬하되, 동일한 값이면 직업이름순 정렬

 

[풀이]

 

- SUBSTR으로 문자열 앞 글자만 자름 

- 문자열 붙이는 CONCAT 함수 사용

-소문자로 바꾸는 LOWER함수 사용

 

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;

 

비교적 수월하게 두 쿼리를 작성했는데 계속 에러가 나서 문제가 뭔가 했더니 해결책은 ; 세미콜론 이었다.

UNION은 두 쿼리의 컬럼 수가 맞아야 하기 때문에 사용하지 못한다.

MySQL은 쿼리 끝에 세미콜론을 쓰지 않아도 되지만

오라클처럼 혹시나 해서 세미콜론을 써보니 결과값이 연달아서 잘 나온다. 

 

+ Recent posts