如何在 SQL 服务器中生成使用其前身值计算的列

How to generate column that calculate with its predecessor value in SQL Server

例如

Amount   ReceivedAmount   PendingAmount
---------------------------------------
 1000         400             600       
  600         400             200

如何在 Amount 列中获取 (600) 个值?

table结构是

1. BillID,Amount,Date from table1

2. BillReceive,ReceiveDate,ReceivedAmount from table2

收到的金额可以是多次的,我想要(Amount - SUM(ReceivedAmount))

的待处理金额

您需要首先加入表 table 1table 2(下面我在 CTE 中这样做了)。然后对上述结果进行自连接以获得累加值。

See working demo

 ; with cte as 
(
 select 
     billid, 
     amount,
     receivedamount, 
     r=row_number() over (partition by t1.billid order by ReceiveDate asc)
 from
  table1 t1 join table2 t2
      on t1.billid=t2.BillReceive
 )

 select 
   amount=max(c1.amount)+max(c1.receivedamount)-sum(c2.receivedamount),
   receivedamount=max(c1.receivedamount),
   pendingamount=max(c1.amount)-sum(c2.receivedamount)
 from 
   cte c1 left join cte c2 
      on c2.r<=c1.r and c2.billid=c1.billid
 group by c1.billid,c1.r