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

相關文章
相關標籤/搜索