Skip to main content

LeetCode 602. Friend Requests II: Who Has the Most Friends SQL Solution

Problem

LeetCode SQL Problem

  1. Friend Requests II: Who Has the Most Friends

request_accepted table

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

Solution

Friend Requests II: Who Has the Most Friends
SELECT TOP 1 ids AS id
,cnt AS num
FROM (
SELECT ids
,count(*) AS cnt
FROM (
SELECT requester_id AS ids
FROM request_accepted

UNION ALL

SELECT accepter_id
FROM request_accepted
) AS tbl1
GROUP BY ids
) AS tbl2
ORDER BY cnt DESC

Query Output

idnum
33