I'm creating a portal with customers with sell/payment options, where all sells are in one table and all payments in another. For customer status table I need to get a sum of all payments per client and all sells per client plus difference between them.
Sample tables:
table clients
====================================
id client_name
====================================
1 School "Mike Jordan"
2 Car wash "Blah blah"
table purchasing
===================================
id client_id amount
===================================
1 1 1000
2 1 500
3 2 800
4 2 800
table payments
===================================
id client_id amount
1 1 300
2 2 200
3 2 200
I have tried with inner join and grouping but this is not getting sum properly, always larger one, like it is counting things I don't want (with no total, just trying to get sums:
select clients.`client_name `,
sum(purchasing.amount) as SOLD,
sum(payments.amount) as PAID
from clients
inner join payments on payments.client_id=clients.id
inner join purchasing on purchasing.client_id=clients.id
group by clients.id
where I got results different (all bigger).
client_name SOLD PAID
================================
School "Mike Jordan" 1500 600
Car wash "Blah blah" 3200 800
If I try to add grouping by payments.id and/or purchasing.id a got more than two results... I know that there is a grouping problem but I really have no idea where it is.
And I wanted to add new column which is just difference between SOLD and PAID, but server generates error with message that SOLD and PAID are not in a field list.
Any idea how to accomplish this with a single query?