title: Aggregate by aggregate (ARRAY_AGG)?
body: <p>Let's say I have a simple table <code>agg_test</code> with 3 columns - <code>id</code>, <code>column_1</code> and <code>column_2</code>. Dataset, for example:</p>
  
  <pre><code>id|column_1|column_2
  --------------------
   1|       1|       1
   2|       1|       2
   3|       1|       3
   4|       1|       4
   5|       2|       1
   6|       3|       2
   7|       4|       3
   8|       4|       4
   9|       5|       3
  10|       5|       4 
  </code></pre>
  
  <p>A query like this (with self join):</p>
  
  <pre><code>SELECT
    a1.column_1,
    a2.column_1,
    ARRAY_AGG(DISTINCT a1.column_2 ORDER BY a1.column_2)
  FROM agg_test a1
  JOIN agg_test a2 ON a1.column_2 = a2.column_2 AND a1.column_1 &lt;&gt; a2.column_1
  WHERE a1.column_1 = 1
  GROUP BY a1.column_1, a2.column_1
  </code></pre>
  
  <p>Will produce a result like this:</p>
  
  <pre><code>column_1|column_1|array_agg
  ---------------------------
         1|       2|      {1}
         1|       3|      {2}
         1|       4|    {3,4}
         1|       5|    {3,4}
  </code></pre>
  
  <p>We can see that for values 4 and 5 from the joined table we have the same result in the last column. So, is it possible to somehow group the results by it, e.g:</p>
  
  <pre><code>column_1|column_1|array_agg
  ---------------------------
         1|     {2}|      {1}
         1|     {3}|      {2}
         1|   {4,5}|    {3,4}
  </code></pre>
  
  <p>Thanks for any answers. If anything isn't clear or can be presented in a better way - tell me in the comments and I'll try to make this question as readable as I can.</p>