[SQL 심화] 리트코드 1문제 :: 602.Friend Requests II: who has the mose friends

Hyeon·2024년 10월 15일

SQL 문제 풀이

목록 보기
28/61

602.Friend Requests II: who has the mose friends

친구 제일 많이 보유한 사람과 count 하여 친구 몇명 보유하고 있는지 출력하기


step 1

우선 accept_date 가 null값이 있는지 확인하였다. 친구 요청했는데 거절하는 경우도 있을 것 같아서 찾아봤는데 null 값 있는 row는 없었다.

select * from RequestAccepted where accept_date is null;

step 2

데이터를 조인해서 제일 많은 친구 수를 보유한 사람 ID와 count 값 출력하기(with cte 활용하기)

우선 union all을 활용해서 요청 id 와 수락 id를 합쳤다.

with cte_1 as (select requester_id as a , accepter_id as b
from RequestAccepted
union all
select accepter_id as a, requester_id as b
from RequestAccepted)

그리고 요청자 id 기준 최대 count을 보유한 상위 id 한 개를 출력하고 count가 몇개인지까지 나오게끔 결과값을 구성하였다.

select a as id ,count(*) as num
from cte_1
group by a
order by 2 desc limit 1
;

결과

0개의 댓글