T-SQL递归更新

T-SQL recursive update

当我更新帐户的收入或结果值时,我应该使用什么查询来更新总计和 Total_previous 列。请注意,记录按 Posting_DataTime 列排序,Transaction_ID 未排序。

Account No Transaction_ID Posting_DataTime Income Outcome Total Total_previous
001 11111111 2021-12-01 00:00 100 null 100 null
001 11112331 2021-12-04 04:00 10 null 110 100
021 11111031 2021-12-04 04:23 1200 null 2000 800
001 11111231 2021-12-08 07:44 null 40 70 110
001 00011231 2021-12-20 11:59 200 null 270 70

如果我将 11112331 (Transaction_ID) 的收入值从 10 更新为 50,则该帐户 (001) 的下一行应该如下所示

Account No Transaction_ID Posting_DataTime Income Outcome Total Total_previous
001 11111111 2021-12-01 00:00 100 null 100 null
001 11112331 2021-12-04 04:00 50 null 150 100
021 11111031 2021-12-04 04:23 1200 null 2000 800
001 11111231 2021-12-08 07:44 null 40 110 150
001 00011231 2021-12-20 11:59 200 null 310 110

您似乎希望将 posting_datatime 由 account_no 排序的(收入 - 结果)相加。一个更好的选择而不是更新是将其作为“视图”而不是每次有变化时都更新。

    create table t(account_no varchar(10),trans_id varchar(1000),posting_datatime datetime,Income int, Outcome int);

    insert
      into t
    select '001','11111111','2021-12-01 00:00',100  ,null union all
    select '001','11112331','2021-12-04 04:00',10   ,null union all
    select '021','11111031','2021-12-04 04:23',1200 ,null union all
    select '001','11111231','2021-12-08 07:44',null ,40  union all
    select '001','00011231','2021-12-20 11:59',200  ,null;

    select account_no
           ,trans_id
           ,posting_datatime
           ,income
           ,outcome
           ,sum(isnull(income,0)-isnull(outcome,0)) 
               over(partition by account_no order by posting_datatime) as total
           ,sum(isnull(income,0)-isnull(outcome,0)) 
               over(partition by account_no order by posting_datatime)
                 -(isnull(income,0)-isnull(outcome,0))as total_prev
      from t
    order by posting_datatime;  

account_no trans_id posting_datatime income outcome total total_prev
001 11111111 2021-12-01 00:00:00.000 100 (null) 100 0
001 11112331 2021-12-04 04:00:00.000 10 (null) 110 100
021 11111031 2021-12-04 04:23:00.000 1200 (null) 1200 0
001 11111231 2021-12-08 07:44:00.000 (null) 40 70 110
001 00011231 2021-12-20 11:59:00.000 200 (null) 270 70

link https://sqlize.online/sql/mssql2017/e86a41327cd213441797c775652f9a69/