lag()函数

h9a6wy2h  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(441)

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

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

但是我想在dif等于0或大于某个值时选择所有的输出。当我输入这个代码时,我得到一个错误。。。

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

我怎么才能解决这个问题?

rmbxnbpk

rmbxnbpk1#

这个 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

笔记:
不需要在减法后面加括号 1 是的第二个参数的默认值 lag() ,因此无需指定

相关问题