I have three tables accounts, receivables and receiveds .
My basic table is receivables I want to get the names from the account table and then subtract the sum of received column in receiveds table form the receivable column in receivables table with same ref numbers. i want to ignore if the balance is zero.
accounts
id | name |
---|---|
22 | John |
23 | Kahn |
24 | Falis |
25 | Haseni |
26 | Gent |
receivables
id | receivable | Ref |
---|---|---|
22 | 70 | A1 |
24 | 100 | A2 |
26 | 60 | A3 |
24 | 15 | A4 |
receiveds
ref | id | received |
---|---|---|
A1 | 22 | 30 |
A2 | 24 | 60 |
A1 | 22 | 40 |
A3 | 26 | 20 |
A2 | 24 | 10 |
desired results
id | name | ref | receivable | received | balance | total_id_balance |
---|---|---|---|---|---|---|
24 | Falis | A2 | 100 | 70 | 30 | 45 |
26 | Gent | A3 | 60 | 20 | 40 | 40 |
24 | Falis | A4 | 15 | 0 | 15 | 45 |
I have tried this code but it’s not working for me
SELECT *
FROM receivables AS rvb
LEFT JOIN accounts AS acc
ON rvb.id = acc.id
LEFT JOIN (SELECT SUM(received) as sum_rvd FROM receiveds) AS rvd
ON acc.id = rvd.id where rvb.receivable>rvd.sum_rvd
3
Answers
This work for me –
EDIT-
Add support for non-unique id in
receivables
INNER JOIN
s filter out NULL values and theHAVING
clause removes zero-balance rows.UPDATE
With a
ref
field we just need to add it as another grouping field for subselects, and change secondINNER JOIN
toLEFT JOIN
(actually looks like it was a mistake from the start, coz we missed entries withoutreceiveds
that still had positive balance). Also changingreceived
field to aCOALESCE
to get zeroes instead of NULL’s (indicating non existing rows in areceiveds
table).Since you need an overall per-id
total_id_balance
field, the natural way to grab it – is using window functions. Note, they are supported only for MySQL 8.0+.So the resulting query looks like this:
Assuming it is possible to have an id in receivables without a corresponding id in receiveds, the second join needs to be a LEFT JOIN and you need to handle the NULLs in your SELECT list –
You can (and should) go a step further and remove the first derived table as it is unnecessary overhead –
db<>fiddle