Sqlserver
 sql >> Base de données >  >> RDS >> Sqlserver

SQL Server Répartition du montant dans la facture

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

Voici une démo sur SqlFiddle .