I have 4 Tables :
1- Suppliers
ID_A | Supplier_name |
---|---|
1 | Apple |
2 | Xiaomi |
3 | Nokia |
4 | Oppo |
2- Start Balance
ID_B | Start Balance |
---|---|
1 | 1000 |
2 | 1000 |
3 | 1000 |
4 | Null |
3- Invoices
ID_C | Invoice_value |
---|---|
1 | 200 |
1 | 500 |
2 | 800 |
3 | 250 |
3 | 400 |
4 | Null |
4- Returns
ID_D | Return_value |
---|---|
1 | 100 |
2 | 50 |
2 | 25 |
3 | Null |
4 | Null |
arithmetic method for the results to show data :
Start Balance + Invoices – Returns = End Balance
i tried to use UNION with JOINS in mysql :
SELECT null , Supplier_name , ID_A , SUM(Invoice_value) , null , null FROM Suppliers
inner JOIN Invoices
ON ID_A = ID_C
group by ID_A
UNION ALL
SELECT null , Supplier_name , ID_A , null , SUM(Return_value), null FROM Suppliers
left JOIN Returns
ON ID_A = ID_D
group by ID_A
UNION ALL
SELECT Start Balance , Supplier_name, ID_A , null , null ,( Start Balance + ifnull(SUM(Invoice_value),0) - ifnull(SUM(Return_value),0) ) FROM Suppliers
left JOIN Start Balance
ON ID_A = ID_B
left JOIN Invoices
ON ID_A = ID_C
left JOIN Returns
ON ID_A = ID_D
group by ID_A
I EXPECT THIS RESULT TO BE :
Start Balance | Supplier_name | ID_A | Invoice_value | Return_value | End_Balance |
---|---|---|---|---|---|
1000 | Apple | 1 | 700 | 100 | 1600 |
1000 | Xiaomi | 2 | 800 | 75 | 1725 |
1000 | Nokia | 3 | 650 | null | 1650 |
null | Oppo | 4 | null | null | null |
but it didnt work well it show the results in differant rows and the calculate of end balance is wrong
please what is the wright code to show this result
2
Answers
You can sum the sums in subquery and join them together
fiddle
I got another solution(Mysql) with CTE…
dbfiddle