SQL每日刷題—day3
阿新 • • 發佈:2020-12-15
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