SQL中基于先前值的动态更新
我正在尝试探索动态更新 我的实际源表是: 更新后源表的预期结果: 我尝试的查询:SQL中基于先前值的动态更新,sql,sql-server,sum,azure-sql-database,window-functions,Sql,Sql Server,Sum,Azure Sql Database,Window Functions,我正在尝试探索动态更新 我的实际源表是: 更新后源表的预期结果: 我尝试的查询: 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 (OR
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
你能帮助我的方法是什么样的吗?我认为这是一个窗口总数:
select
t.*,
1 + coalesce(
sum(length) over(
order by key
rows between unbounded preceding and 1 preceding
),
0
) new_begin_pos
from mytable t
您可以像这样使用SUM()
窗口函数:
select
[key],
sum(length) over (order by [key]) - length + begin_pos begin_pos,
length
from tab
如果要更新表,请执行以下操作:
with cte as (
select *, sum(length) over (order by [key]) - length + begin_pos new_begin_pos
from tab
)
update cte
set begin_pos = new_begin_pos
请参阅。结果:
很 完美。希望我必须在更新查询中使用这个临时表来获得最终结果?您的问题中没有临时表,@Madan。
> key | begin_pos | length
> --: | --------: | -----:
> 1 | 1 | 1
> 2 | 2 | 9
> 3 | 11 | 3
> 4 | 14 | 7
> 5 | 21 | 3
> 6 | 24 | 6
> 7 | 30 | 16