Возможно, этот запрос удовлетворит ваши требования.
Данные испытаний:
drop table if exists Customer;
drop table if exists Cusfindata;
drop table if exists Custtrn;
create table Customer (
id int identity,
code int,
name varchar(30)
);
create table Cusfindata (
id int identity,
custid int,
amount numeric(10,0)
);
create table Custtrn (
id int identity,
invoicenumber int,
custid int,
amount numeric(10,0),
invoicedate date
);
insert into Customer(code,name)
values ( 100 , 'Dimitris' ), ( 102 , 'George' ), ( 104 , 'John' );
insert into Cusfindata( custid, amount)
values ( 100, 100 ) , ( 102 , 50 ) , ( 104 , 80 );
insert into Custtrn(invoicenumber,custid,amount,invoicedate)
values ( 1 , 100 , 50 , '20180701' ) , ( 2 , 100 , 30 , '20180708' ) ,
( 3 , 102 , 20 , '20180715' ) , ( 4 , 102 , 56 , '20180722' ) ,
( 5 , 104 , 54 , '20180729' ) , ( 6 , 100 , 80 , '20180805' ) ,
( 7 , 104 , 150 , '20180812' ) , ( 8 , 102 , 20 , '20180819' ) ,
( 9 , 102 , 23 , '20180826' ) , ( 10 , 102 , 60 , '20180902' ) ,
( 11 , 100 , 40 , '20180909' ) , ( 12 , 100 , 20 , '20180916' ) ,
( 13 , 104 , 20 , '20180923' ) , ( 14 , 104 , 30 , '20180930' ) ,
( 15 , 100 , 60 , '20181007' ) , ( 16 , 100 , 10 , '20181014' ) ;
Решение:
with my_summary as (
select c.code,
c.name,
cf.amount as limit,
ct.invoicedate,
ct.invoicenumber,
ct.amount [invoice amount],
SUM(ct.amount) over (partition by c.code order by ct.invoicedate desc,ct.invoicenumber desc) [total to pay]
from Customer c
join Cusfindata cf on c.code = cf.custid
join Custtrn ct on c.code = ct.custid
-- exclude invoices with amount greater than limit
where ct.amount <= cf.amount
)
select s.*
from my_summary s
where s.[total to pay] <= s.limit;
Результаты: