首页 > 解决方案 > SQL 中基于先前值的动态更新

问题描述

我正在尝试探索动态更新。

我的实际源表是:

在此处输入图像描述

更新后源表的预期结果:

在此处输入图像描述

我试过的查询:

WITH t AS
(
    SELECT key,
           Begin_POS,
           Length,
           (Begin_POS+ Length) as res
    from   tab
)
SELECT src_column_id,
       Length,res,
       COALESCE(Length + lag(res) OVER (ORDER BY src_column_id),1)  AS PRE_VS
from t

你能帮助我的方法应该是什么吗?

标签: sqlsql-serversumazure-sql-databasewindow-functions

解决方案


我认为这是一个窗口总和:

select 
    t.*,
    1 + coalesce(
        sum(length) over(
            order by key 
            rows between unbounded preceding and 1 preceding
        ), 
        0
    ) new_begin_pos
from mytable t

推荐阅读