22,210
社区成员
发帖
与我相关
我的任务
分享
select A.*,
case when B.n>=subtotal then 0 when subtotal-A.n<B.n and subtotal>B.n then subtotal-B.n else A.n end as balance
from #cc A
join #aa B ON A.t=B.t
outer apply (select SUM(n) as subtotal from #cc where A.t=t and id<=A.id) as C