홍동이의 성장일기
[LeetCode] 602. Friend Requests II: Who Has the Most Friends 본문
Tool/SQL 코딩테스트 풀이
[LeetCode] 602. Friend Requests II: Who Has the Most Friends
홍동2 2023. 4. 17. 16:06
with cte_unionall as(
select requester_id as id
from RequestAccepted
union all
select accepter_id as id
from RequestAccepted
)
, cte_count as(
select id, count(id) num
from cte_unionall
group by 1
)
select id, num
from cte_count
order by num desc
limit 1
🔄️ 2023.08.14 다시 풀어본 쿼리
WITH cte_re AS(
SELECT requester_id id
, COUNT(accepter_id) num
FROM requestaccepted
GROUP BY requester_id
)
, cte_ac AS(
SELECT accepter_id id
, COUNT(requester_id) num
FROM requestaccepted
GROUP BY accepter_id
)
, cte_union AS(
SELECT *
FROM cte_re
UNION ALL
SELECT *
FROM cte_ac
)
SELECT id
, SUM(num) num
FROM cte_union
GROUP BY id
ORDER BY num desc
LIMIT 1
💡 개념정리
UNION
- 쿼리의 결과를 합친다.
- 중복된 ROW는 제거 (DISTINCT)
UNION ALL
- 모든 컬럼값이 같은 ROW도 결과를 보여준다.
- 중복제거X
728x90
'Tool > SQL 코딩테스트 풀이' 카테고리의 다른 글
[LeetCode] 183. Customers Who Never Order (0) | 2023.08.12 |
---|---|
[LeetCode] 1179. Reformat Department Table (0) | 2023.08.12 |
[HackerRank] Type of Triangle (0) | 2023.04.17 |
[HackerRank] The PADS (0) | 2023.04.17 |
[LeetCode] 175. Combine Two Tables (0) | 2023.04.17 |
Comments