[Hackerrank] SQL - Challenges

DMIS·2022년 3월 12일
0

SQL

목록 보기
31/48
post-thumbnail

문제

풀이

이 문제 하나 푸는데 거의 2시간이 걸렸다.
처음에는 쉽게 접근하다가 문제의 조건인 아래 2가지를 해결하는데 정말 애먹었다.

  • total 값이 중복이 되면 그 행은 보여주지 않는다.
  • 그러나 total 값이 최댓값이면 중복이어도 보여준다.

처음에는

max(count(challenge_id))

와 같이 집계함수 안에 집계함수를 넣는 정말 신박하고 멍청한 방법을 떠올렸다.

이후 서브쿼리를 많이 써서 해결하자는 전략으로 하나씩 해결해보았다.

  1. total 값이 중복이 되는 행 걸러내기
    count, group by를 사용하였다.
select total 
from (select hacker_id, count(challenge_id) as total
	  from challenges as sub1
      group by hacker_id) as sub2
group by sub2.total
having count(sub2.total)=1
  1. total의 최댓값 구하기
    max, group by를 사용하였다.
select max(C4.total)
from (select hacker_id, count(challenge_id) as total
	  from challenges as sub3
      group by hacker_id) as sub4
  1. 1번과 2번을 조합하여 문제에서 원하는 hacker_id, name, total 값을 정렬 순서대로 맞춰 조회하였다.
select H.hacker_id, H.name, count(C.challenge_id) as total 
from hackers as H
join challenges as C
on H.hacker_id = C.hacker_id
group by H.hacker_id, H.name
having total in (select C2.total
                 from (select hacker_id, count(challenge_id) as total
                       from challenges as C1
                       group by hacker_id) as C2
                 group by C2.total
                 having count(C2.total)=1)
    or total = (select max(C4.total)
               from (select hacker_id, count(challenge_id) as total
                     from challenges as C3
                     group by hacker_id) as C4)
order by total desc, H.hacker_id

느낀점

  • 그동안 문제를 풀면서 테이블의 alias를 t1, t2와 같이 사용하였는데 이 문제를 풀면서 살짝 혼란이 왔다.
    그래서 H, C와 같이 사용하려고 했으나 서브쿼리를 작성하는 과정에서 결국 C1, C2와 같이 되었다.
    alias를 보기 쉽고 간편하게 짓는 것도 나름 중요해보인다.
    • 열의 alias도 마찬가지다. 처음에는 total을 totall, totalll과 같이 서브쿼리마다 다른 alias를 지어줬는데, 이런 것이 필요 없다는 것을 미리 인지할 필요가 있다.
profile
Data + Math

0개의 댓글