合并两个表并使用按 FIFO 排序

Combine two tables and use sort by FIFO

我被 MySQL 查询困住了。

第一个 table 只包含一个 loan_number 的贷款。


(loan_number, tranche_number, daydate, bills),

(555555, 1,'2020-01-01', 100),

(555555, 2,'2020-01-06', 100)

第二个 table 包含付款。


(loan_number, daydate, bills)

(555555,'2020-01-02', -10),

(555555,'2020-01-03', -10),

(555555,'2020-01-04', -10),

(555555,'2020-01-05', -20),

(555555,'2020-01-07', -50),

(555555,'2020-01-10', -100),

(555555,'2020-01-11', -10)

我需要按 FIFO 顺序合并上面的两个 table(首先是贷款,然后是该贷款的付款次数)。 结果应该是这样的。

(loan_number, tranche_number, daydate, bills),

(555555, 1,'2020-01-01', 100 ),

(555555, 1,'2020-01-02', -10 ),

(555555, 1,'2020-01-03', -10 ),

(555555, 1,'2020-01-04', -10 ),

(555555, 1,'2020-01-05', -20 ),

(555555, 1,'2020-01-07', -50 ),

(555555, 2,'2020-01-06', 100 ),

(555555, 2,'2020-01-10', -100),

(555555, 2,'2020-01-11', -10)

听起来你想要 union all。然而,诀窍是获得tranch_number。注意:给定的付款可能有多个档次。以下应return 最早付款:

select loan_number, tranche_number, daydate, bills
from table1
union all
select t2.loan_number, t1.tranche_number, t2.daydate, t2.bills
from (select t2.*,
             sum(bills) over (partition by loan_number order by daydate) as running_bills
      from table2 t2
     ) t2 join
     (select t1.*,
             sum(bills) over (partition by loan_number order by daydate) as running_bills
      from table1 t1
     ) t1
     on - (t2.running_bills - t2.bills) >= t1.running_bills - t1.bills and
        - t2.running_bills <= t1.running_bills;

请注意,这需要 MySQL 8+。

Here 是一个 db<>fiddle.