본문 바로가기
프로그래밍/Python 관련 정보

[SQL문제풀이-Union의 활용] Friend Requests II

by TrillionNT 2025. 4. 13.

2025.02.24 - [프로그래밍/SQL, Hive, SAS 관련 정보] - [SQL] Table of Contents


https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends/description/?envType=study-plan-v2&envId=top-sql-50

 

원래 저는 oracle의 subquery 및 CTE를 이용해서 풀었는데, 다른 사람의 솔루션 중에서 곱씹어볼만한 부분이 있어서 체크해보려고 합니다. 보통 우리가 union이나 union all를 사용하는 경우에는 칼럼 정보가 균질적인 녀석들을 대상으로 행만 확장하는 상황을 생각하기 쉬운데요. 사실 실제 테이블의 칼럼정보는 상이하더라도 문제 상황에서 우리가 필요한 부분만 타겟으로 놓고 생각해봤을 때 균질적이라면 union (all)을 활용하는 것도 방법이라고 할 수 있겠습니다. 

 

select id,count(*) as num
from (
select requester_id as id
from RequestAccepted

UNION ALL

select accepter_id as id
from RequestAccepted
) as friend_count
group by id
order by num desc
limit 1