SQL Server Partition by ID and Add or Subtract Preceding Row



我试图计算基于开放余额和事件类型的ID的关闭余额

下面是样本数据

tbody> <<tr>131313103939394141475152525355
ID Date_Opened Opening_Amount Event_Date Event_Amount Event_Remark
1312/31/20197498612/31/201974986打开
12/31/2019749862/17/202074984付款
12/31/2019749865/4/202074984
12/31/2019749867/19/20212关闭
9/10/20202500009/10/2020250000打开
5/26/20211170755/7/2021117075打开
5/26/20211170757/14/202145467付款
5/26/20211170758/17/202122083付款
6/3/20211290965/26/2021129096打开
6/3/20211290968/13/2021122772付款
486/30/2021423506/25/202142350打开
486/30/2021423508/3/202142196付款
7/23/20211009806/24/2021100980打开
7/28/2021814587/15/202181458打开
7/30/2021467507/27/202146750打开
7/30/2021467508/24/202146750付款
8/6/2021451008/2/202145100打开
8/11/2021437258/9/202143725打开

嗯…你应该能够使用窗口函数:

select t.*,
(case when Event_Remark = 'Open' then Event_Amount
when Event_Remark = 'Close' then 0
else sum(case when Event_Remark = 'Open' then event_amount else 0) over (partition by id order by date_opened) +
sum(case when Event_Remark = 'Reversal' then event_amount else 0) over (partition by id order by date_opened) -
sum(case when Event_Remark = 'Payment' then event_amount else 0) over (partition by id order by date_opened)
end) as closing_balance
from t;

注意:这里假设最多有一个"Open"one_answers";Close"每个帐户和"开放";是第一行和"close"。最后一行

相关内容

  • 没有找到相关文章

最新更新