Sql 服务器在同一上下文中滞后?

Sql Server Lag in same context?

我需要从 table 获取之前的 ID,但我想将之前的记录限制为给定的 ID,即 id_sucursal(分支),因为如果我不这样做,第一行(id_sucursal)将从另一个 sucursal 获得 previous_id(滞后)。 我知道我可以订购 id_sucursal 并且工作正常,但我想将它保持在相同的 id_sucursal 上下文中,这是 select 语句,非常简单,不需要更多。

Select

    -- current id
    t.id,

    -- when i order everything is ok but on the first row 
    -- I get the id from another sucursal
    lag(id) OVER (ORDER BY t.id_sucursal) prev_id,

    -- here sucursal may be different
    t.id_sucursal

    From sucursal_info

做这样的事情会很棒:

Select

    t.id,

    lag(id) OVER (ORDER BY t.id_sucursal) (WHERE id_sucursal = t.id_sucursal) prev_id,

    --
    t.id_sucursal

    From sucursal_info

当然还有更多行,但我只是带来了需要的行来解释这一点。

这是短信中的另一个例子:

看来您需要添加 partition by clause in LAG

....
lag(id) OVER (parition by id_sucursal ORDER BY id_sucursal) prev_id. 
.....

此外,我没有看到您将 table 的别名设置为 t,但您将列引用为 t.column_name。因此我删除了它