title: How to combine DISTINCT and ORDER BY in array_agg of jsonb values in postgresSQL
body: <p>Note: I am using the latest version of Postgres (9.4)</p>
  
  <p>I am trying to write a query which does a simple join of 2 tables, and groups by the primary key of the first table, and does an array_agg of several fields in the 2nd table which I want returned as an object.  The array needs to be sorted by a combination of 2 fields in the json objects, and also uniquified.</p>
  
  <p>So far, I have come up with the following:</p>
  
  <pre class="lang-sql prettyprint-override"><code>SELECT  
    zoo.id,  
    ARRAY_AGG(
      DISTINCT ROW_TO_JSON(( 
        SELECT x  
        FROM ( 
          SELECT animals.type, animals.name 
        ) x
      ))::JSONB
      -- ORDER BY animals.type, animals.name
    )
    FROM zoo
    JOIN animals ON animals.zooId = zoo.id
    GROUP BY zoo.id;
  </code></pre>
  
  <p>This results in one row for each zoo, with a an aggregate array of jsonb objects, one for each animal, uniquely.</p>
  
  <p>However, I can't seem to figure out how to also sort this by the parameters in the commented out part of the code.</p>
  
  <p>If I take out the distinct, I can ORDER BY original fields, which works great, but then I have duplicates.</p>