In my database I have a table, payers_payments
, consisting of some foreign keys (payer_id
, payment_id
) and some pivot fields (amount
, pays
).
| id | payer_id | payment_id | amount | pays |
|----|----------|------------|--------|------|
| 1 | 1 | 1 | 20 | 0 |
| 2 | 2 | 1 | 23 | 1 |
| 4 | 1 | 2 | 14 | 1 |
| 5 | 2 | 2 | 17 | 1 |
| 6 | 1 | 3 | 10 | 1 |
| 7 | 2 | 3 | 0 | 0 |
Each row represents a contribution a payer
made towards a payment
. The pays
field specifies whether that payer
should be included in the payment.
The total cost of a payment
is the sum of amount
for a given payment_id
. So if I wanted to see how much payment 2 cost I would run:
SELECT SUM(amount) AS sumOfPayment
FROM payers_payments
WHERE payment_id=2;
Likewise the total amount a given payer
(say, payer 1) has contributed is:
SELECT SUM(amount) AS sumOfPayment
FROM payers_payments
WHERE payer_id=1;
Now, what I want to do is use the concept of fair share. Fair share is the total cost of the payment divided by the number of payers
who have pay=1
for that payment. The simplest way I can express this is with a sub-query:
SELECT SUM(payers_payments.amount) / (SELECT count(*)
FROM payers_payments
WHERE pays
AND payers_payments.payment_id = 3
) AS FairShare
FROM payers_payments
WHERE payment_id=3
GROUP BY
payers_payments.payment_id;
For a given payer
and payment
their fair share is defined as:
SELECT IF(pays, FairShare, 0) as payerFairShare
FROM payers_payments
WHERE payer_id = 1
AND payment_id=3; --FairShare is the query as above
My question is that I want a query to get the total fair share for each payer
based on the fair share of each payment and whether or not they are included in the payment. (If pays=false
then their fair share is 0)
Based on the above data this is the kind of result I'm after for the 2 payers:
| payer_id | total_paid | fair_share |
|----------|------------|------------|
| 1 | 44 | 25.5 |
| 2 | 40 | 58.5 |
Is there a way to achieve this in a single query or must I do some looping of result sets? I am agnostic on RDMS but something MySQL-like is good.