with data as ( select '2020-04-15' as day,'收入' as type,'test1' as name,100 as amt, 5000 as bal union all select '2020-04-16' as day,'支出' as type,'test1' as name,10 as amt, null as bal union all select '2020-04-17' as day,'支出' as type,'test1' as name,20 as amt, null as bal union all select '2020-04-15' as day,'收入' as type,'test2' as name,200 as amt, 2000 as bal union all select '2020-04-18' as day,'支出' as type,'test2' as name,40 as amt, null as bal ) select t2.day ,t2.type ,t2.name ,t2.amt ,t2.amt_flag ,sum(t2.amt_flag) over(partition by name order by day ) as amt_new from ( select t1.* ,case when type = '收入' then amt else - amt end as amt_flag from ( select '1900-01-01' as day,'收入' as type, name, bal as amt, null as bal from data where bal is not null union all select * from data ) t1 ) t2 ;