例如
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))
答案 0 :(得分:1)
您需要先将表table 1
和table 2
(在CTE中这样做)联接起来。然后对上述结果进行自我连接以获得累积值。
; 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