title: Full outer join on multiple tables in PostgreSQL
body: <p>In PostgreSQL, I have <code>N</code> tables, each consisting of two columns: <code>id</code> and <code>value</code>. Within each table, <code>id</code> is a unique identifier and <code>value</code> is numeric.</p>
  
  <p>I would like to join all the tables using <code>id</code> and, for each <code>id</code>, create a sum of <code>value</code>s of all the tables where the <code>id</code> is present (meaning the id may be present only in subset of tables).</p>
  
  <p>I was trying the following query:</p>
  
  <pre><code>SELECT COALESCE(a.id, b.id, c.id) AS id,
         COALESCE(a.value,0) + COALESCE(b.value,0) + COALESCE(c.value.0) AS value
  FROM
    a
      FULL OUTER JOIN
    b
      ON (a.id=b.id)
      FULL OUTER JOIN
    c
      ON (b.id=c.id)
  </code></pre>
  
  <p>But it doesn't work for cases when the <code>id</code> is present in <code>a</code> and <code>c</code>, but not in <code>b</code>.</p>
  
  <p>I suppose I would have to do some bracketing like:</p>
  
  <pre><code>SELECT COALESCE(x.id, c.id) AS id, x.value+c.value AS value
  FROM
      (SELECT COALESCE(a.id, b.id), a.value+b.value AS value
       FROM
         a
           FULL OUTER JOIN
         b
           ON (a.id=b.id)
      ) AS x
        FULL OUTER JOIN
      c
        ON (x.id = c.id)
  </code></pre>
  
  <p>It was only 3 tables and the code is ugly enough already imho. Is there some elegant, systematic ways how to do the join for <code>N</code> tables? Not to get lost in my code?</p>
  
  <p>I would also like to point out that I did some simplifications in my example. Tables <code>a</code>, <code>b</code>, <code>c</code>, ..., are actually results of quite complex queries over several materialized views. But the syntactical problem remains the same.</p>