[英]How to use alias in where clause in mysql with lead lag functions
[英]Lag() function with WHERE clause
我有這個正常工作的 sql function:
SELECT out_hum ,
(out_hum - LAG(out_hum, 1) OVER (ORDER BY id)) As dif
FROM excel_table
但是我想 select 當差異(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
我該如何解決這個問題?
where
子句不能訪問select
子句中定義的表達式的別名(因為基本上前者在后者之前處理)。 最重要的是,對 window 函數有一個特殊限制,它不能出現在查詢的where
子句中(它們只允許在select
一個order 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()
的第二個參數的默認值,因此無需指定
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.