윈도우함수 vs 윈도우함수 없이 무지성 서브쿼리 사용하기

반응형

https://www.hackerrank.com/challenges/challenges/problem

SQLD를 공부하면서 윈도우함수에 대해서 이해했다고 생각했는데,, 아직 실습에서 사용하려니 손에 익지 않았던 모양이다. 위 문제를 풀면서 뭔가 굉장히 비효율적이고 불편한 느낌이 있었는데 윈도우 함수를 사용하면 훨씬 깔끔하게 풀렸다.

챌린지 개수가 챌린지 개수 중에서 가장 많거나, 챌린지 개수 그룹별 개수를 산출했을 때 1이면 출력하라는 조건을 구현해야 했다. 우선 내가 무지성 서브쿼리로 작성한 쿼리를 첨부한다.

select x.id, x.name, x.count_ch
from 
    (select h.hacker_id id, h.name name, count(c.hacker_id) count_ch
        from hackers h, challenges c
        where h.hacker_id=c.hacker_id
        group by h.hacker_id, h.name) x, 
    (select count_ch, count(count_ch) condition_ch
        from (select h.hacker_id, h.name, count(c.hacker_id) count_ch
                from hackers h, challenges c
                where h.hacker_id=c.hacker_id
                group by h.hacker_id, h.name)
        group by count_ch) y,
    (select max(count_ch) max_ch
        from (select h.hacker_id, h.name, count(c.hacker_id) count_ch
                from hackers h, challenges c
                where h.hacker_id=c.hacker_id
                group by h.hacker_id, h.name)) z
where x.count_ch=y.count_ch
and (y.condition_ch=1 or z.max_ch=x.count_ch)
order by 3 desc, 1;

자세히보면 x,y,z 간 거의 비슷한 내용을 조회하고 있어 굉장히 심적으로 불편한 느낌이 든다. 하지만 그룹함수 max를 활용하기 위해서는 어쩔수가 없었다....고 생각했다.

다른 사람들은 어떻게 풀었나 살펴보다가 뭔가 굉장히 깔끔해보이는 코드를 발견했다. 자세히보니 나도 분명히 아는 내용인데?? 윈도우 함수를 이럴 때 쓰는구나 하는 생각에 바로 코드를 적어내려갔다.

select id, name, totalch
from (select id, name, totalch, count(totalch) over (partition by totalch) as count_number, max(totalch) over () as maxcount
from (select h.hacker_id as id, h.name as name, count(c.hacker_id) as totalch
        from hackers h inner join challenges c
        on h.hacker_id=c.hacker_id
        group by h.hacker_id, h.name)
     )
where count_number=1 or totalch=maxcount
order by totalch desc, id;

group by를 활용한 그룹함수는 row수가 변하기 때문에 이 문제에서는 활용하기 어려웠던 반면

윈도우함수는 row수를 변화시키지 않고 partition by 기준에 의해 집계하기 때문에 서브쿼리 수를 깔끔히 줄일 수 있었다.

 

오늘도 이론공부만 할 게 아니라 코테 대비도 열심히 해야겠구나 하는 생각이 든다.

 

 

'데이터 공부 > SQL 실전문제' 카테고리의 다른 글

Oracle SQL 실전문제 풀이 (2)  (0) 2022.08.26
Oracle SQL 실전문제 풀이 (1)  (0) 2022.08.24