1. 程式人生 > 資料庫 >Leetcode SQL 刷題 601題

Leetcode SQL 刷題 601題

Leetcode SQL 刷題


題目描述

體育館的人流量

編寫一個 SQL 查詢以找出每行的人數大於或等於 100 且 id 連續的三行或更多行記錄。
返回按 visit_date 升序排列的結果表。

stadium
Result table


一、分析思路

1.自連線
找到連續三條記錄以上的id,並且滿足三條記錄均大於等於100
首先三個表自連線,第一條查詢語句找出三條記錄的第一個ID
第二條查詢語句找出三條記錄的第二個ID
第三條查詢語句找出三條記錄的第三個ID

   (SELECT s1.Id
    FROM Stadium s1,Stadium s2,Stadium s3
    WHERE (s1.Id=s2.Id-1 AND s2.Id=s3.Id-1) AND
    (s1.people>=100 and s2.people>=100 and s3.people>=100) )
    UNION 
    (SELECT s2.Id
    FROM Stadium s1,Stadium s2,Stadium s3
    WHERE (s1.Id=s2.Id-1 AND s2.Id=s3.Id-1) AND
    (s1.people>=100 and s2.people>=100 and s3.people>=100) )
    UNION
    (SELECT s3.Id
    FROM Stadium s1,Stadium s2,Stadium s3
     WHERE (s1.Id=s2.Id-1 AND s2.Id=s3.Id-1) AND
    (s1.people>=100 AND s2.people>=100 AND s3.people>=100))  
     

根據找到的Id對Stadium進行篩選和排序

SELECT *
FROM Stadium 
WHERE Id IN (
    (SELECT s1.Id
    FROM Stadium s1,Stadium s2,Stadium s3
    WHERE (s1.Id=s2.Id-1 AND s2.Id=s3.Id-1) AND
    (s1.people>=100 and s2.people>=100 and s3.people>=100) )
    UNION 
    (SELECT s2.Id
    FROM Stadium s1,Stadium s2,Stadium s3
    WHERE (s1.Id=s2.Id-1 AND s2.Id=s3.Id-1) AND
    (s1.people>=100 and s2.people>=100 and s3.people>=100) )
    UNION
    (SELECT s3.Id
    FROM Stadium s1,Stadium s2,Stadium s3
     WHERE (s1.Id=s2.Id-1 AND s2.Id=s3.Id-1) AND
    (s1.people>=100 AND s2.people>=100 AND s3.people>=100))
    ORDER BY visit_date ASC

2.使用基本語法查詢
在表 stadium 中查詢人流量超過 100 的記錄,將查詢結果與其自身的臨時表連線,再使用 WHERE 子句獲得滿足條件的記錄。
第一步:查詢人流量超過 100 的記錄,然後將結果與其自身的臨時表連線。
第二步: 篩選出連續記錄大於等於三條的行,
表 t1,t2 和 t3 相同,需要考慮新增哪些條件能夠得到想要的結果。以 t1 為例,它有可能是連續三天的第 1 天,第 2 天,或第 3 天。

SELECT DISTINCT S1.*
FROM  Stadium S1, Stadium S2, Stadium S3
WHERE S1.people >= 100 AND S2.people >= AND S3.people >= 100
     AND
    (
        (S1.id - S2.id = 1 AND S1.id - S3.id = 2 AND S2.id - S3.id =1)-- S1, S2, S3
        OR
        (S2.id - S1.id = 1 AND S2.id - S3.id = 2 AND S1.id - S3.id =1)-- S2, S1, S3
        OR
        (S3.id - S2.id = 1 AND S2.id - S1.id =1 AND S3.id - S1.id = 2)-- S3, S2, S1
    )
ORDER BY  S1.id