如何在SQL Server中生成使用其前值计算的列

时间:2018-12-30 15:25:15

标签: sql-server sql-server-2008

例如

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

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

表结构为

1. BillID,Amount,Date from table1

2. BillReceive,ReceiveDate,ReceivedAmount from table2

已收金额可以是多次,我要从(Amount - SUM(ReceivedAmount))

提取待处理金额

1 个答案:

答案 0 :(得分:1)

您需要先将表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