比较当前行与上一行-LeetCode解决方案

时间:2019-11-30 02:01:03

标签: sql join

我正在尝试了解以下leetcode问题的解决方案: https://leetcode.com/problems/rising-temperature/

给出的解决方案如下:

SELECT weather.id AS 'Id'
FROM weather
JOIN
weather w ON DATEDIFF(weather.date, w.date) = 1
AND weather.Temperature > w.Temperature;

该问题需要计算当前行温度和先前温度之间的增量。在上面的解决方案中这是如何实现的?似乎在左右表的同一行之间进行了比较。

3 个答案:

答案 0 :(得分:1)

由于表中的数据采用每个日期一个值的形式,因此前一个温度的RecordDate值是早一天的值,因此要对表中的值进行JOIN进行比较在这种情况下(即DATEDIFF(w2.RecordDate, w1.RecordDate) = 1),以及新行的温度高于上一行(w2.Temperature > w1.Temperature)的条件,即

SELECT *
FROM Weather w1
JOIN Weather w2 ON DATEDIFF(w2.RecordDate, w1.RecordDate) = 1
               AND w2.Temperature > w1.Temperature

如果查看该查询的所有输出值,则可以看到对于每一行,RecordDate的{​​{1}}值比w2晚一天,而温度为w1高于w2

w1

因此,从该结果来看,仅选择Id RecordDate Temperature Id RecordDate Temperature 1 2015-01-01 00:00:00 10 2 2015-01-02 00:00:00 25 3 2015-01-03 00:00:00 20 4 2015-01-04 00:00:00 30 值即是一个问题

w2.Id

输出

SELECT w2.Id AS Id
FROM Weather w1
JOIN Weather w2 ON DATEDIFF(w2.RecordDate, w1.RecordDate) = 1
               AND w2.Temperature > w1.Temperature

Demo on dbfiddle

答案 1 :(得分:1)

JOIN条件是将一行的数据连接到上一行。我认为使用日期算法会更明显:

SELECT w.id
FROM weather w JOIN
     weather wprev
     ON wprev.date = w.date - interval 1 day
WHERE w.Temperature > wprev.Temperature;

这甚至可以利用(date)上的索引。

也就是说,更明显的解决方案是lag() -这就是您应该学习的内容:

select w.*
from (select w.*,
             lag(temperature) over (order by date) as prev_temperature
      from weather w
     ) w
where prev_temperature < temperature;

答案 2 :(得分:0)

这是我的解决方案:

SELECT table1.Id as 'Id'
FROM Weather as table1
INNER JOIN Weather as table2
ON datediff(table1.RecordDate, table2.RecordDate) = 1
and table1.Temperature> table2.Temperature;