【问题标题】:Lag() function with WHERE clause带有 WHERE 子句的 Lag() 函数
【发布时间】:2020-09-04 19:30:38
【问题描述】:

我有这个正常工作的 sql 函数:

SELECT out_hum ,
 (out_hum - LAG(out_hum, 1) OVER (ORDER BY id)) As dif
FROM excel_table

但是当差异 (dif) 等于 0 或大于某个值时,我想选择所有 out_hum。当我输入此代码时,我得到一个错误...

SELECT out_hum ,
 (out_hum - LAG(out_hum, 1) OVER (ORDER BY id)) As dif
FROM excel_table  WHERE dif=0

我该如何解决这个问题?

【问题讨论】:

    标签: mysql sql select where-clause window-functions


    【解决方案1】:

    where 子句不能访问select 子句中定义的表达式的别名(因为基本上,前者在后者之前处理)。最重要的是,窗口函数有一个特殊的限制,它不能出现在查询的where 子句中(它们只能出现在selectorder by 子句中)。

    典型的解决方案是使用派生表,例如子查询:

    select *
    from (
        select out_hum, out_hum - lag(out_hum) over (order by id) as dif
        from excel_table
    ) t
    where dif = 0
    

    注意事项:

    • 不需要加括号

    • 1lag()的第二个参数的默认值,所以不需要指定

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 1970-01-01
      • 2012-03-25
      • 1970-01-01
      • 2014-03-26
      • 2017-01-15
      • 2020-11-29
      相关资源
      最近更新 更多