프로젝트(진행중)/MySQL
HackerRank 공부 1
일말고프로젝트
2023. 3. 6. 15:15
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
문제 핵심
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을 활용해서 컬럼을 합치는 방법
2. UNILON ALL 활용해서 테이블 합치기
3. 위 아래 테이블 서로 다르게 ORDER BY 하기
내 풀이
SELECT t2.DD
FROM (SELECT CONCAT(NAME, CONCAT('(', SUBSTRING(OCCUPATION, 1,1), ')')) AS DD FROM OCCUPATIONS ORDER BY DD LIMIT 9999999999) AS t2
UNION
SELECT CONCAT('There are a total of ', t1.cnt, CONCAT(' ', lower(t1.Occupation), 's.')) as DD
FROM (SELECT Occupation, count(Name) as cnt
FROM OCCUPATIONS
GROUP BY Occupation
ORDER BY cnt, Occupation LIMIT 9999999999) AS t1
;
다른사람 풀이
select
concat(name,'(',left(occupation,1),')')
as a
from occupations
union
select
concat('There are a total of ',count(occupation),' ',lower(occupation),'s.')
as b
from occupations
group by occupation
order by a;
몰랐던 부분
ORDER BY 할 때 SUBQUERY 안에 넣었다고 해도 UNION ALL 하면 최적화 되면서 ORDER BY가 풀려버리기 때문에 LIMIT를 추가해줘야 안 풀린다. ORDER BY가 UNION 보다 늦게 평가 되기 때문임..
- LEFT : 문자에 왼쪽을 기준으로 일정 갯수를 가져오는 함수.
- MID : 문자에 지정한 시작 위치를 기준으로 일정 갯수를 가져오는 함수.
- RIGHT : 문자에 오른쪽을 기준으로 일정 갯수를 가져오는 함수.