title: PostgreSQL aggregate union, intersection and set differences
body: <p>I have a table of pairs to aggregate as follows:</p>
  
  <pre><code>+---------+----------+
  | left_id | right_id |
  +---------+----------+
  | a       | b        |
  +---------+----------+
  | a       | c        |
  +---------+----------+
  </code></pre>
  
  <p>And a table of values as so:</p>
  
  <pre><code>+----+-------+
  | id | value |
  +----+-------+
  | a  | 1     |
  +----+-------+
  | a  | 2     |
  +----+-------+
  | a  | 3     |
  +----+-------+
  | b  | 1     |
  +----+-------+
  | b  | 4     |
  +----+-------+
  | b  | 5     |
  +----+-------+
  | c  | 1     |
  +----+-------+
  | c  | 2     |
  +----+-------+
  | c  | 3     |
  +----+-------+
  | c  | 4     |
  +----+-------+
  </code></pre>
  
  <p>For each pair, I would like to calculate the length of the union, intersection and set differences (each way) comparing the values, so that the output would look like this:</p>
  
  <pre><code>+---------+----------+-------+--------------+-----------+------------+
  | left_id | right_id | union | intersection | left_diff | right_diff |
  +---------+----------+-------+--------------+-----------+------------+
  | a       | b        | 5     | 1            | 2         | 2          |
  +---------+----------+-------+--------------+-----------+------------+
  | a       | c        | 4     | 3            | 0         | 1          |
  +---------+----------+-------+--------------+-----------+------------+
  </code></pre>
  
  <p>What would be the best way to approach this using PostgreSQL?</p>
  
  <p>UPDATE: here is a rextester link with data <a href="https://rextester.com/RWID9864" rel="nofollow noreferrer">https://rextester.com/RWID9864</a></p>