3

我有以下表格

LINEID   BILL   Total Amount     Allocated Amount
1         1         100             
2         1         200
3         2         250

PAYID    BILL    Paid Amount
1         1         250
2         2         100

我需要根据账单在第一张桌子上分配支付金额。我知道我可以将游标与 WHILE 循环一起使用并分配 - 有没有更好的方法来做到这一点?

结果应该是

LINEID   BILL   Total Amount     Allocated Amount
1         1         100             100
2         1         200         150
3         2         250         100
4

1 回答 1

3
WITH  cl AS
(select o.LINEID, o.BILL, o.[Total Amount], 
(select SUM([Total Amount]) from bills t where o.BILL = t.BILL and o.LINEID >= t.LINEID) as 'sum_total_ammount'
from bills o inner join payment p on o.BILL = p.BILL)

select o.LINEID, o.BILL, o.[Total Amount], 
case when p.[Paid Amount] >= sum_total_ammount then o.[Total Amount] 
else (o.[Total Amount] - sum_total_ammount + p.[Paid Amount]) end as 'Allocated Amount'
from cl o inner join payment p on o.BILL = p.BILL
and (o.[Total Amount] - sum_total_ammount + p.[Paid Amount]) > 0

这是关于SqlFiddle的演示。

于 2013-09-17T23:39:22.583 回答