如何在哪里使用LEAD和LAG?

时间:2014-11-11 12:27:49

标签: sql-server lag lead

我有一张这样的桌子:

Number   Price    Type       Date         Time
------   -----    ----    ----------    ---------
23456    0,665     SV     2014/02/02     08:00:02
23457    1,3       EC     2014/02/02     07:50:45
23460    0,668     SV     2014/02/02     07:36:34
23461    0,668     SV     2014/02/02     07:37:34
23462    0,668     SV     2014/02/02     07:38:34
23463    0,668     SV     2014/02/02     07:39:34

对于每条记录,我需要上一个/下一个价格。在这种情况下,查询很简单。

Select Lag(price) over (order by date desc, time desc),
Lead(price) over (order by date desc, time desc)
from ITEMS

但我需要结果其中下一个价格<>记录价格

我的查询

    Select Lag(price) over (order by date desc, time desc) Nxt_Price,
    Lead(price) over (order by date desc, time desc) Prv_Price
    from ITEMS
 Where Nxt_Price <> price

但它拒绝使用该变量

2 个答案:

答案 0 :(得分:5)

尝试以下查询:

SELECT Nxt_Price, Prv_Price 
FROM
    (Select price, Lag(price) over (order by date desc, time desc) Nxt_Price,
    Lead(price) over (order by date desc, time desc) Prv_Price
    from ITEMS) AS InnerQuery
 Where Nxt_Price <> price

它可能对你有帮助。

答案 1 :(得分:1)

使用公用表表达式。

with myItems as (
     Select Lag(price) over (order by date desc, time desc) Nxt_Price,
    Lead(price) over (order by date desc, time desc) Prv_Price
    from ITEMS
)
select *
from myItems
where Nxt_Price <> Prv_Price