Zend certified PHP/Magento developer

EXCEL – Sum fixed range based in complex multiple criteria

I have 3 tables:

  1. SALES
    Sale ID
    Provider Sell Count ID
    Client
    Provider
    Commission

  2. COMMISSION PAYMENTS
    Sales Range
    Provider
    Amount Payed

  3. COMMISSION AGENTS
    Client
    Agent Name
    Commission %

I need to calculate the amount that corresponds to each Commission Agent only from commissions that were already paid.

To do so i should use Sales Range in Commission Payments table and get all sales that are within that range and are from same provider in Sales table.

The Sales Range comes from the Provider Sell Count ID field in Sales Table.
That way i can have a record of which sales commissions have been payed for each provider.

Then i have to check for each of them who’s the client, check whose agent is that client from (based on the data on the third table) and multiply the commission amount by the commission percentage that corresponds to him.

I guess i should use some complex combination of MATCHs and INDEXs but couldnt get it to work, any ideas?

I hope i made myself clear.