【问题标题】:Dynamic update in SQL based on previous valueSQL 中基于先前值的动态更新
【发布时间】:2020-08-21 07:56:18
【问题描述】:

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

我的实际源表是:

更新后源表的预期结果:

我试过的查询:

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

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

【问题讨论】:

    标签: sql sql-server sum azure-sql-database window-functions


    【解决方案1】:

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

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

    【讨论】:

    • 完美。希望我必须将其用作更新查询中的临时表才能获得最终结果?
    • 你的问题中没有临时表,@Madan。
    【解决方案2】:

    你可以像这样使用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
    

    请参阅demo
    结果:

    > 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
    

    【讨论】:

      猜你喜欢
      • 2018-03-03
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      • 2013-03-17
      • 2022-01-15
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      相关资源
      最近更新 更多