Skip to content
Advertisement

How to join two total tables using sql?

For a university work we have two tables in sql:

table1:

         column_name1      number_P1
           PARIS             10
           LISBOA            20
           RIO               30

table2:

         column_name2      number_P2
           PARIS             100
           NEW YORK          300

I need to join the two tables by adding the total number of people in each city. So I tried to do:

SELECT table1.column_name1,
       number_P2 + number_P1 AS TOTAL       
       
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;

However, if a city A appears in table 1 and does not appear in table 2 this would not work. The same would happen if a City B appears in table 2 and does not appear in table 1. How can I generalize these situations?

Desired output:

         column_name      number_P
           PARIS             110
           LISBOA            20
           RIO               30
           NEW YORK          300

Advertisement

Answer

We can try to use UNION ALL with SUM instead of JOIN

SELECT column_name, 
       SUM(number_P) number_P
FROM (
    SELECT column_name1 as column_name,number_P1 as number_P
    FROM table1 
    UNION ALL
    SELECT column_name2,number_P2
    FROM table2
) t1
GROUP BY column_name      
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement