홍동이의 성장일기

[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

 

 

Friend Requests II: Who Has the Most Friends - LeetCode

Can you solve this real interview question? Friend Requests II: Who Has the Most Friends - Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

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
Comments