Coding/SQL

[LeetCode-SQL 50] 602. Friend Requests II: Who Has the Most Friends

kangplay 2025. 2. 28. 18:01
문제

https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends/description/

설명

친구 요청을 한 사람이던, 받은 사람이던 상관 없이 친구가 가장 많은 회원의 id과 친구 수를 출력하는 문제이다.

union all 과 서브 쿼리를 사용한다면 어렵지 않은 문제이다.

 

최댓값을 구해야하므로, 서브쿼리를 가지고 max 값을 구하고, 그 값을 where 절에서 비교해주어야한다. 

구현
# Write your MySQL query statement below
with TOTAL_USERS as
    ( select requester_id as id
    from RequestAccepted
    union all
    select accepter_id as id
    from RequestAccepted ),

    FRIEND_COUNT as 
    ( select id, count(*) as num
        from TOTAL_USERS
        group by id )


select *
from FRIEND_COUNT
where num = (select max(num) from FRIEND_COUNT) ;