使用滞后窗口函数的 SQL 查询出错

Error in SQL query with lag windowing function

我正在 Leetcode 上写一个 problem 关于 SQL。该问题给出了一个名为 Weather 的 table,其中包含 Id(如温度测量的 id)、TemperatureRecordDate 的条目。每个 Id 来自随后的一天。他们要求 Id 当天的温度超过前一天的温度。

我的尝试是

select id
    from
        (select id, temperature, lag(temperature, 1) over (ORDER BY RecordDate) prevs
            from weather)
    where temperature > prevs  

但它告诉我 (ORDER BY... 部分附近存在语法错误。

怎么了?

您的查询语法不正确:

首先,如果您将 LAG() 与位置参数一起使用,那么您还必须指定第三个参数。但是,默认情况下它是 1。因此,不需要指定:

LAG(temperature) over (ORDER BY RecordDate) AS prevs_temp

其次,您的子查询没有别名:

select t.id
from (select id, temperature, LAG(temperature) over (ORDER BY RecordDate) AS prevs_temp
      from weather
     ) t -- alias missing 
where (t.temperature > t.prevs_temp or t.prevs_temp is null); -- will return id which doesn't have previous `temperature`.