SQL每日刷題—day3

SQL—day3

題目

編寫一個 SQL 查詢,來查找與之前(昨天的)日期相比溫度更高的所有日期的 id 。

查詢結果格式如下例:

Weather
+----+------------+-------------+
| id | recordDate | Temperature |
+----+------------+-------------+
| 1  | 2015-01-01 | 10          |
| 2  | 2015-01-02 | 25          |
| 3  | 2015-01-03 | 20          |
| 4  | 2015-01-04 | 30          |
+----+------------+-------------+
Result table:
+----+
| id |
+----+
| 2  |
| 4  |
+----+

2015-01-02 的溫度比前一天高(10 -> 25)
2015-01-04 的溫度比前一天高(20 -> 30)

預備知識

Mysql中有DATEDIFF函數,求兩個日期的天數差集

DATEDIFF(被減數, 減數) 

例如:

SELECT DATEDIFF('2020-12-14','2020-12-13') AS DiffDate 

1
SELECT DATEDIFF('2020-12-13','2020-12-14') AS DiffDate 

1


@ 定義用戶變量
@@ 引用或定義全局變量

= 只有在set和update時纔是和:=一樣,賦值的作用,其它都是等於的作用

:= 不只在set和update時時賦值的作用,在select也是賦值的作用

因此用變量實現行號時,必須用:=

思路

1. weather表格做自聯結,連接條件需要同時滿足’溫度關係‘&’日期差異‘,從鏈接後的表格查詢出所有ID

2. 定義日期、溫度變量,循環利用布爾標誌符判斷

代碼

基本查詢

select a.Id 
from  Weather as a 
join Weather as b 
on a.Temperature > b.Temperature and dateDiff(a.RecordDate,b.RecordDate)= 1 

變量

select
    Id
from
    (select w.*,
     @curd := w.RecordDate,
     @curt := w.Temperature,
     @isH := if(datediff(@curd,@pred) = 1 and @curt > @pret,1,0) as r,
     @pret := @curt,
     @pred := @curd
    -- @pret := w.Temperature,   與上方等價
    -- @pred := w.RecordDate  與上方等價
     from   Weather as w
     order by w.RecordDate
    ) t
where
    t.r = 1
    

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/rising-temperature

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章