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_id | accepter_id | accept_date |
+--------------+-------------+-------------+
| 1 | 2 | 2016/06/03 |
| 1 | 3 | 2016/06/08 |
| 2 | 3 | 2016/06/08 |
| 3 | 4 | 2016/06/09 |
+--------------+-------------+-------------+
Output:
+----+-----+
| id | num |
+----+-----+
| 3 | 3 |
+----+-----+
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.
테이블: RequestAccepted
Column Name Type
requester_id | int |
accepter_id | int |
accept_date | date |
(requester_id, accepter_id)는 이 테이블의 기본 키(각 행이 고유한 값을 가지는 컬럼 조합)입니다.
이 테이블은 친구 요청을 보낸 사용자의 ID(requester_id), 요청을 받은 사용자의 ID(accepter_id), 요청이 수락된 날짜(accept_date)를 포함합니다.
문제 요구사항
가장 많은 친구를 가진 사람의 ID와 해당 친구 수를 구하는 SQL 쿼리를 작성하세요.
테스트 케이스는 오직 한 명의 사용자만 가장 많은 친구를 가지도록 설정됩니다.
출력 형식은 아래 예제를 따릅니다.
예제 1
입력 데이터 (RequestAccepted 테이블)
requester_id accepter_id accept_date
1 | 2 | 2016/06/03 |
1 | 3 | 2016/06/08 |
2 | 3 | 2016/06/08 |
3 | 4 | 2016/06/09 |
출력 결과
id num
3 | 3 |
설명
사용자 ID 3은 다음과 같이 3명의 친구를 가지고 있습니다.
- 1번 사용자
- 2번 사용자
- 4번 사용자
다른 누구보다도 많은 친구를 가지고 있으므로, id = 3, num = 3이 출력됩니다.
WITH ids AS (
# 1. requester_id와 accepter_id는 중복이 없이 각자의 친구가 명시된 컬럼이므로 union all로 합친다.
# 그렇게 되면 (2를 친구로 가지고 있는 1) & (1을 친구로 가지고 있는 2) 두 케이스 모두 반영 가능해진다.
SELECT requester_id AS id FROM requestaccepted
UNION ALL
SELECT accepter_id FROM requestaccepted
)
SELECT
# 2. group by id 로 id 별 행 개수를 세면 id 별 가지고 있는 친구 수가 나온다.
id,
COUNT(*) AS num
FROM ids
GROUP BY
id
# 3. 친구 수 내림차순 -> 첫 행만 추출
ORDER BY
num DESC
LIMIT 1
'[SQL]' 카테고리의 다른 글
LeetCode 코딩 테스트 - Market Analysis I(LV.Medium) (0) | 2025.03.11 |
---|---|
LeetCode 코딩 테스트 - Monthly Transactions I(LV.Medium) (0) | 2025.03.10 |
LeetCode 코딩 테스트 - Customers Who Bought All Products(LV.Medium) (0) | 2025.03.05 |
LeetCode 코딩 테스트 - Rank Scores(LV.Medium) (0) | 2025.03.03 |
LeetCode 코딩 테스트 - Last Person to Fit in the Bus(LV.Medium) (0) | 2025.03.02 |