I don’t have a name for this. So feel free to let me know if this is a known algo.
Basically I have buyers and sellers, sorted by quantity. I want to match the buyer/seller in terms of quantities, starting from highest qty. If the other side does not have enough, it finds the next biggest supplier. One can be matched with multiple suppliers.
Below is an example:
Buyer 1/2/3/4 with qty of: +200, +120, +80, +50
Seller 1/2/3/4 with qty of: -160, -120, -70, -30
The matches I want are (B1 = Buyer 1, S1 = Seller 1):
B1 -> S1 and S2 (160 from S1, 40 from S2)
S1 -> B1 (B1 has more than 160)
B2 -> S1, S2 (both S1 and S2 have more than 120)
S2 -> B1, B2 (both B1 and B2 have more than 120)
B3 -> S1, S2 (only S1 and S2 have more than 80)
S3 -> B1, B2, B3 (B1, B2, B3 have more than 70)
B4 -> S1, S2, S3
S4 -> B1, B2, B3, B4
What I need is SQL implementation of this, not python or other programming languages.