If you want to update your table with sql
in SQL Server
you can do something like this:
i use two updates for your table and in the first one update the columns with amn
and 0
with tab as
(select
id,dat,amn,(select max(id) from mytable) as maxid,
case when typ = 'd' then 0 else amn end as flwc,
case when typ = 'c' then 0 else amn end as flwd,
typ,
0 as rn,0 as totalc,0 as totalD
from mytable)
update mytable set
mytable.flwc = tab.flwc,mytable.flwd = tab.flwd
from mytable inner join tab on mytable.id = tab.id;
in the second one sum them:
with tab2 as
(select
t1.id,t1.dat,x.d
from mytable t1
CROSS APPLY (SELECT SUM(v)
FROM ( SELECT TOP(select count(*) from mytable) b.flwd
FROM mytable b
WHERE b.id <= t1.id
ORDER BY b.id DESC ) x(v)
) x(d)),
tab3 as
(select
t1.id,t1.dat,x.c
from mytable t1
CROSS APPLY (SELECT SUM(v)
FROM ( SELECT TOP(select count(*) from mytable) b.flwc
FROM mytable b
WHERE b.id <= t1.id
ORDER BY b.id DESC ) x(v)
) x(c)),
tab4 as (select tab2.id,tab2.dat,tab2.d,tab3.c from tab2,tab3 where tab2.id = tab3.id),
tab5 as (select t4.id,t4.dat,t4.amn,tab4.c as flwc,tab4.d as flwd,t4.typ
from mytable t4,tab4
where t4.id = tab4.id)
update mytable set
mytable.flwc = tab5.flwc,mytable.flwd = tab5.flwd
from mytable inner join tab5 on mytable.id = tab5.id;