602. Friend Requests II: Who Has the Most Friends
Write a solution to find the people who have the most friends and the most friends number.
The test cases are generated so that only one person has the most friends.
The result format is in the following example.
친구가 가장 많은 사람의 id와 친구의 수를 구하는 문제다. 이 문제 역시 생각이 좀 필요한데, 아래의 쿼리는 requester_id와 accepter_id 컬럼을 UNION ALL로 하나로 합친 다음, id를 GROUP BY를 통해 가장 많은 숫자를 가진 id를 추출하는 방식으로 풀이했다.
UNION ALL
을 하면 테이블이 아래와 같다.
id |
---|
1 |
1 |
2 |
3 |
2 |
3 |
3 |
4 |
WITH most_friend AS
(SELECT requester_id id FROM RequestAccepted
UNION ALL
SELECT accepter_id id FROM RequestAccepted)
SELECT id
,COUNT(id) AS num
FROM most_friend
GROUP BY id
ORDER BY num DESC
LIMIT 1