SQL练习——LeetCode解题和总结(2)

602. Friend Requests II: Who Has the Most Friends[M]

1、表信息spa

In social network like Facebook or Twitter, people send friend requests and accept others' requests as well.3d

table:request_acceptedcode

2、题目信息blog

找出拥有好友数最多的用户编号及其拥有的好友数。全部的请求默认都被处理了。ci

注意:rem

  • 只有一个用户拥有最多的好友数
  • 好友邀请只能被接受一次,所以要去除重复值

 For the sample data above, the result is:requests

3、参考SQLit

 1 WITH t1 AS ( SELECT DISTINCT requester_id, accepter_id FROM request_accepted597 ),
 2 t2 AS ( SELECT requester_id AS id FROM t1 ),
 3 t3 AS ( SELECT accepter_id AS id FROM t1 )
 4 
 5 SELECT * 
 6 FROM
 7     ( SELECT
 8         id,
 9         count( * ) AS num 
10     FROM( SELECT id FROM t2 UNION ALL SELECT id FROM t3 ) temp 
11     GROUP BY id 
12     ) t 
13 ORDER BY num DESC 
14 LIMIT 1;

思路:io

(你加别人或者别人加你,你都多了一个好友。因此不管你的ID是出如今requester_id仍是accepter_id,都证实你多了一个好友)table

一、t1用于去重。由于两个相同用户之间发送屡次请求和接受,都只能算是同一个好友。(生活中的场景:之前初中用QQ的时候,暗恋同班一个女童鞋,要到了她的QQ,周一到周五晚上一放学就去网吧打毒奶粉,顺便加女神的QQ,可是女神没有回应,因而周一到周五天天都加了一次,谁知道女神是好同窗,只有周五回家才上网,她周五回到家了把我周一到周五发送的全部请求加好友消息都赞成了,我瞬间有了五个女友,嘻嘻。。。)

二、去重以后,用t2和t3分别把请求和相应的ID都提取出来,在union all把他们拼接在一块儿,获得temp表

三、此时问题就转化为id出现次数最多的问题了。分组——统计个数——倒序——截取第一个最大值便可

(PS:这里默认本身不能加本身为好友,也就是requester_id不等于accepter_id。记得之前QQ能够给本身发好友请求的。倘若最多好友数不止一我的,或者求好友数前三的信息。就和前面的一些题目很李相似)

方法二:网友答案

 1 SELECT c.people as id, SUM(c.cnt) AS num
 2 FROM (
 3 SELECT requester_id AS people, COUNT(DISTINCT accepter_id) AS cnt
 4 FROM request_accepted
 5 GROUP BY requester_id
 6 
 7 UNION ALL   
 8 
 9 SELECT accepter_id AS people, COUNT(DISTINCT requester_id) AS cnt
10 FROM request_accepted
11 GROUP BY accepter_id 
12 ) AS c
13 
14 GROUP BY c.people
15 ORDER BY SUM(c.cnt) DESC
16 LIMIT 1;

思路:

一、子查询1:本身主动加了几我的

二、子查询2:有几我的主动加了我

三、把两个子查询拼接起来,就是我一共有几个好友

(PS:思路差很少,这两个子查询用的很妙,可是前提仍是本身不能加本身为好友。注意union all 和 union distinct的区别!)

603. Consecutive Available Seats[E]

1、表信息

cinema表为某电影院选座状况,包含座位编号以及座位是否可选。

Several friends at a cinema ticket office would like to reserve consecutive available seats.

2、题目信息

找出连续座位的编号。

Can you help to query all the consecutive available seats order by the seat_id using the following cinema table?

注意:

  • 座位编号是自动递增的整数型数据,是否可选是一个逻辑值 (1表明可选,0表明不可选)
  • 连续座位可选指至少连续的两个座位是能够选的

Note:

  • The seat_id is an auto increment int, and free is bool ('1' means free, and '0' means occupied.).
  • Consecutive available seats are more than 2(inclusive) seats consecutively available.

Your query should return the following result for the sample case above.

3、参考SQL

相关文章
相关标签/搜索