๐ข ๋ณธ ํฌ์คํ ์ ํ์ฉ๋๋ ๊ธฐ๋ณธ ๋ฌธ์ ๋ฐ ์๋ฃ ์ถ์ฒ๋
๋ฆฌํธ์ฝ๋ Problems, https://leetcode.com/problemset/all/์์ ๋ฐํ๋๋ค.
โ ๋ฌธ์
https://leetcode.com/problems/friend-requests-ii-who-has-the-most-friends/description/
Friend Requests II: Who Has the Most Friends - LeetCode
Can you solve this real interview question? Friend Requests II: Who Has the Most Friends - Table: RequestAccepted +----------------+---------+ | Column Name | Type | +----------------+---------+ | requester_id | int | | accepter_id | int | | accept_date |
leetcode.com
Table : RequestAccepted
Write an SQL query 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 query result format is in the following example.
Example 1:
โ ํ์ด
๋ฌธ์ ์๊ตฌ์ฌํญ
์น๊ตฌ๊ฐ ๊ฐ์ฅ ๋ง์ ์ฌ๋์ id์ ์น๊ตฌ ์๋ฅผ ์ถ๋ ฅํด์ผ ํ๋ค.
๋จ ์์๋ฅผ ๋ณด๋ฉด requester ๊ธฐ์ค์ผ๋ก accepter ๊ฐ ์น๊ตฌ ๊ด๊ณ๊ฐ ๋์ง๋ง
request ํ ์ ์ด ์์ด๋ accepter๊ฐ ๋๋ฉด requester์ ์น๊ตฌ ๊ด๊ณ๋ก ๋ณด๋ ๊ฒ์ด ์ค์ํ๋ค.
๋ฐ๋ผ์ ๋จ์ํ๊ฒ accepter๋ฅผ requester๋ก ๋ณผ ์ ์๋๋ก ์ปฌ๋ผ์ ๋ค์ง์ด์ ์ํ ๊ฒฐํฉํด์ฃผ๊ธฐ ์ํด UNION ALL์ ์ฌ์ฉํ๋ค.
๊ฒฐํฉ ํ ์ด๋ธ์ ๋ํด์ requester_id ์ปฌ๋ผ์ ๊ธฐ์ค์ผ๋ก ์ฐ๊ฒฐ ๊ด๊ณ๋ฅผ ์ง๊ณํ๋ฉด,
๊ฒฐ๊ณผ์ ์ผ๋ก requester ↔ accepter ๋ฐฉํฅ ๊ด๊ณ์์ด id๋ณ๋ก ์น๊ตฌ ๊ด๊ณ๋ฅผ ์ง๊ณํ ์ ์๋ค.
SELECT requester_id AS id,
COUNT(accepter_id) AS num
FROM (
SELECT requester_id, accepter_id
FROM RequestAccepted
UNION ALL
SELECT accepter_id, requester_id
FROM RequestAccepted
) T1
GROUP BY 1
ORDER BY 2 DESC
LIMIT 1
'Growth ๐ณ > Practice ๐ป' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 1045. Customers Who Bought All Products (0) | 2023.05.18 |
---|---|
[LeetCode] 608. Tree Node (0) | 2023.05.16 |
[LeetCode] 601. Human Traffic of Stadium (0) | 2023.05.11 |
[LeetCode] 577. Employee Bonus (0) | 2023.05.10 |
[LeetCode] 585. Investments in 2016 (0) | 2023.05.09 |