leetcode -數據庫 - 197. 上升的溫度 - over()和join解決


      
      原題:https://leetcode-cn.com/problems/rising-temperature/
      我自己做leetcode的數據庫題目的解題記錄:
              解題目錄 https://blog.csdn.net/weixin_42845682/article/details/105196004

題目

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

+---------+------------------+------------------+
| Id(INT) | RecordDate(DATE) | Temperature(INT) |
+---------+------------------+------------------+
|       1 |       2015-01-01 |               10 |
|       2 |       2015-01-02 |               25 |
|       3 |       2015-01-03 |               20 |
|       4 |       2015-01-04 |               30 |
+---------+------------------+------------------+ 

       例如,根據上述給定的 Weather 表格,返回如下 Id:

+----+
| Id |
+----+
|  2 |
|  4 |
+----+

答案

第一種答案 - join

       我以爲日期和id都是升序的,所以sql如下:

select
    w2.id id
from weather w1
join weather w2 on w1.id = w2.id-1
where w2.temperature > w1.temperature 

       後來發現,有可能id升序,日期降序。所以改成如下:

select
    w2.id id
from weather w1
join weather w2 on w1.recordDate = w2.recordDate-1
where w2.temperature > w1.temperature 

      但是報錯了…可我記得可以直接用加減操作日期啊…
       換成函數,果然對了…

select
    w2.id id
from weather w1
join weather w2 on DATEDIFF(w2.recordDate, w1.recordDate) = 1
where w2.temperature > w1.temperature 

第二種答案 - over()

       其實這道題over()也能做,但是leetcode裏的mysql好像不支持over()(mysql8.0好像支持over()了),所以就用oracle做。

select
    id 
from(
    select
        id id,
        recordDate d,
        temperature t,
        lag(temperature) over(order by recordDate) as tt,
        lag(recordDate) over(order by recordDate) as td,
        lag(id) over(order by recordDate) as tid  
    from weather 
) tmp 
where t>tt 

      然後報錯了,我看了一下,輸入的數據只有兩條,id是升序,但是日期根本不是前一天後一天的關係…這也可以???
      改一下sql…

select
    id 
from(
    select
        id id,
        recordDate d,
        temperature t,
        lag(temperature) over(order by recordDate) as tt,
        lag(recordDate) over(order by recordDate) as td,
        lag(id) over(order by recordDate) as tid  
    from weather 
) tmp 
where t>tt
and d-td=1

       嗯,發現tid那行沒啥用啊…刪了刪了

select
    id 
from(
    select
        id id,
        recordDate d,
        temperature t,
        lag(temperature) over(order by recordDate) as tt,
        lag(recordDate) over(order by recordDate) as td
    from weather 
) tmp 
where t>tt
and d-td=1

       但是發現一個奇怪的問題:
在這裏插入圖片描述
       有紅框的是有多餘的tid的sql執行的時間,沒有紅框的,是沒有tid的sql執行的時間。
       怎麼執行了多餘的語句,消耗時間還少了那麼多???
       總感覺leetcode對oracle不是支持的很好…
       順便吐槽一下,你想了好多細節的時候,leetcode告訴你你想多了;你不想那麼多的時候,你就又會感慨出一堆:臥槽,這也可以。

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