오랑우탄의 반란
LeetCode 리트코드 | 602. Friend Requests II: Who Has the Most Friends (MySQL) 본문
SQL/LeetCode
LeetCode 리트코드 | 602. Friend Requests II: Who Has the Most Friends (MySQL)
5&2 2024. 8. 7. 11:11반응형
오늘도 오랑이는 문제를 풉니다.
602. Friend Requests II: Who Has the Most Friends


풀이 과정
- requester_id 와 accepter_id 칼럼에서 가장 자주 등장한 수 = id
- id 가 등장한 회수 카운트 = num
친구추가는 한쪽이 하면 자동으로 다른쪽도 한거와 마찬가지기 때문에
requester_id 와 accepter_id 두 칼럼 모두에서 가장 많이 등장한 수를 찾아야 합니다.
즉 두 칼럼을 union해서 개수를 세어야 합니다.
select requester_id as id from RequestAccepted
union all
select accepter_id as id from RequestAccepted

여기에서 id별로 그룹하고 개수를 센 칼럼 num 기준으로 내림차순 정렬하면 각 id별로 몇명의 친구가 있는지 확인할 수 있습니다.
with cte as (
select requester_id as id from RequestAccepted
union all
select accepter_id as id from RequestAccepted
)
select id, count(*) as num from cte group by 1 order by 2 desc

가장 많은 사람 1명만 추출하는 거기 때문에 limit을 걸어줍니다.
최종 코드
with cte as (
select requester_id as id from RequestAccepted
union all
select accepter_id as id from RequestAccepted
)
select id, count(*) as num from cte group by 1 order by 2 desc limit 1
오랑우탄이 영어를 하고 오랑이가 쿼리마스터가 되는 그날까지~
https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends/
반응형
'SQL > LeetCode' 카테고리의 다른 글
LeetCode | 1484. Group Sold Products By The Date (MySQL) GROUP_CONCAT 그룹별 행 한줄에 출력 (0) | 2024.08.19 |
---|---|
LeetCode 리트코드 | 185. Department Top Three Salaries (MySQL) DENSE_RANK (0) | 2024.08.08 |
LeetCode 리트코드 | 1321. Restaurant Growth (MySQL) (0) | 2024.08.05 |
LeetCode 리트코드 | 1341. Movie Rating (MySQL) (0) | 2024.08.02 |
LeetCode 리트코드 | 626. Exchange Seats (MySQL) CASE, LAG/LEAD, ROW_NUMBER (0) | 2024.08.01 |