Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL duplicate rows subtraction in different tables MySQL

I have a problem with subtraction of sums of values from different tables. That’s what I mean. First table:

id_p | num
-----------
1    | 5
2    | 3

Second table:

id_p | num
-----------
1    | 2
1    | 2
2    | 1

And the result must be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

id_p | res
-----------
1    | 1
2    | 2

So for id_p = 1 it must be 5 – 2 – 2 = 1, and for id_p = 2 3 – 1 = 2.
But I receive such result:

id_p | res
-----------
1    | 6
2    | 2

It dublicates 5 in inner, left, right, cross joins, so it’s always gives me (5 + 5) – (2 + 2), not a 5 – (2 + 2). Please, help me to understand how to do this in MySQL. Also it must work in both ways.

UPD: there might be another columns, so they also can affect on the duplicating.

>Solution :

One approach joins to a subquery which finds ths sums:

SELECT t1.id_p, t1.num - COALESCE(t2.num, 0) AS res
FROM table1 t1
LEFT JOIN
(
    SELECT id_p, SUM(num) AS num
    FROM table2
    GROUP BY id_p
) t2
    ON t2.id_p = t1.id_p
ORDER BY t1.id_p;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading