LeetCode 602. Friend Requests II: Who Has the Most Friends SQL Solution
Problem
LeetCode SQL Problem
- Friend Requests II: Who Has the Most Friends
request_accepted 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 |
Solution
- MySQL
- TSQL
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
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
id | num |
---|---|
3 | 3 |