602. Friend Requests II: Who Has the Most Friends

김요한·2024년 9월 30일
0

리트코드

목록 보기
7/7
post-thumbnail

Table: RequestAccepted

+----------------+---------+
| Column Name | Type |
+----------------+---------+
| requester_id | int |
| accepter_id | int |
| accept_date | date |
+----------------+---------+
(requester_id, accepter_id) is the primary key (combination of columns with unique values) for this table.
This table contains the ID of the user who sent the request, the ID of the user who received the request, and the date when the request was accepted.

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.

Example 1:

Input:
RequestAccepted table:

requester_idaccepter_idaccept_date
122016/06/03
132016/06/08
232016/06/08
342016/06/09

Output:

idnum
33

Explanation:
The person with id 3 is a friend of people 1, 2, and 4, so he has three friends in total, which is the most number than any others.

Follow up: In the real world, multiple people could have the same most number of friends. Could you find all these people in this case?

문제 정의

  • 가장 친구가 많은 ID 와 그 친구의 수를 가져오자

첫번째로 친구 요청을 한 친구의 수와 ID를 가져온다.

select requester_id
,count(requester_id)
from RequestAccepted
group by requester_id

requester_idcount(requester_id)
12
21
31

두번째로 친구 요청을 받은 친구의 수와 ID를 가져온다.

select accepter_id
,count(requester_id)
from RequestAccepted
group by accepter_id

accepter_idcount(requester_id)
21
32
41
with many_person as
(( 
select requester_id
        ,count(requester_id) as num
from RequestAccepted
group by requester_id
)
union all
(
select accepter_id 
        ,count(requester_id) 
from RequestAccepted
group by accepter_id 
))
select requester_id as id , sum(num) as num 
from many_person
group by requester_id
order by num desc
LIMIT 1

Output:

idnum
33

WITH문에서 두 테이블을 UNION ALL로 중복포함 수직결합 한 후

친구가 가장 많은 테이블을 상위 1개 추출한다.

0개의 댓글