高频 SQL 50 题(基础版) - 学习计划 - 力扣(LeetCode)全球极客挚爱的技术成长平台
602. 好友申请 II :谁有最多的好友
题目:
编写解决方案,找出拥有最多的好友的人和他拥有的好友数目。
生成的测试用例保证拥有最多好友数目的只有 1 个人。
Create table If Not Exists RequestAccepted (requester_id int not null, accepter_id int null, accept_date date null);
Truncate table RequestAccepted;
insert into RequestAccepted (requester_id, accepter_id, accept_date) values ('1', '2', '2016/06/03');
insert into RequestAccepted (requester_id, accepter_id, accept_date) values ('1', '3', '2016/06/08');
insert into RequestAccepted (requester_id, accepter_id, accept_date) values ('2', '3', '2016/06/08');
insert into RequestAccepted (requester_id, accepter_id, accept_date) values ('3', '4', '2016/06/09');
解析:
好友都是相互的,A向B提交了好友申请,那么A是B的好友,同时,B也是A的好友。
第一步:
所以联合‘好友邀请’的人、‘同意好友’的人
select requester_id id from requestaccepted
union all
select accepter_id id from requestaccepted
第二步:
计算每个人记录在表的数量
with tb as (
select requester_id id from requestaccepted
union all
select accepter_id id from requestaccepted
)
select id, count(*) num from tb group by id
第三步:
过滤
with tb as (
select requester_id id from requestaccepted
union all
select accepter_id id from requestaccepted
)
select id, count(*) num from tb group by id order by num desc limit 1;
标签:RequestAccepted,accepter,SQL50,力扣,好友,requester,id,select,刷题
From: https://blog.csdn.net/wyl_0831/article/details/142997760