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告诉你你想多了;你不想那么多的时候,你就又会感慨出一堆:卧槽,这也可以。

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