Skip to content Skip to sidebar Skip to footer

Merge Tables With Postgresql

The title of this question is not accurate but I didn't know how to summarize it. Please feel free to write it again if you can! Here is an extract of two tables: Table table_a cod

Solution 1:

yu probably are looking for FULL OUTER JOIN

SELECT
  coalesce(a.code,b.code),
  coalesce(a."year",b.year),
  coalesce(a.nb_a,0),
  coalesce(b.nb_b,0),
  coalesce(a.nb_a,0) + coalesce(b.nb_b,0) AS total
FROM table_a a full outer join table_b b on a.code = b.code and a.year = b.year;
 coalesce | coalesce | coalesce | coalesce | total
----------+----------+----------+----------+-------
        1 |     2013 |        0 |        1 |     1
        1 |     2014 |        0 |        1 |     1
        1 |     2017 |        1 |        0 |     1
        2 |     2012 |        2 |        1 |     3
        3 |     2014 |        2 |        0 |     2
(5 rows)

Post a Comment for "Merge Tables With Postgresql"