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

MySQL merge two tables and get sum

i have a tableA:

+------+--------+-------+
| name | code   | num   |
+------+--------+-------+
| A    | no1    | 300   |
| A    | no2    | 100   |
+------+--------+-------+

i also have a tableB:

+------+--------+-------+
| name | code   | num   |
+------+--------+-------+
| A    | no1    | -100  |
| A    | no5    | 77    |
| B    | no7    | 2     |
+------+--------+-------+

My goal is want to get tableC like this:

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

+------+--------+-------+
| name | code   | num   |
+------+--------+-------+
| A    | no1    | 200   |
| A    | no2    | 100   |
| A    | no5    | 77    |
| B    | no7    | 2     |
+------+--------+-------+

i used union and join,but the result is not right,please tell me how to get TableC?

>Solution :

So, instead of JOIN what you need is UNION. You can use "UNION ALL" or "UNION", it depends if you want the duplicated rows or not.

In any case, after the UNION, group that result into a subquery to get the SUM()

SELECT
u.name,
u.code,
SUM(u.num),
FROM
(
SELECT name, code, num FROM tableA
UNION ALL
SELECT name, code, num FROM tableB
) u
GROUP BY u.name, u.code
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