title: Sort conditional data in Postgres STRING_AGG
body: <p>I've come up with a query to create concatenated string based on a conditional statement using <code>STRING_AGG</code> in Postgress. That works just fine but I want to sort the result as well without duplicating the <code>CASE</code>.</p>
  
  <p>This is what I have now:</p>
  
  <pre><code>SELECT
  STRING_AGG(distinct name, ', ' ORDER BY name),
  STRING_AGG(
    DISTINCT
    CASE WHEN something = true THEN 'type1'
         WHEN something_else = true THEN 'type2'
         ELSE 'type3'
    END, ', '
  ORDER BY
    CASE WHEN something = true THEN 'type1'
         WHEN something_else = true THEN 'type2'
         ELSE 'type3'
    END
  
  )
  from organisations
  </code></pre>
  
  <p>..but I want to do something like this to not have the duplicated code and remove rows and complexity from my query but I can't figure out how to make it work, this is fake code that doesn't work obviously, but you get the idea:</p>
  
  <pre><code>SELECT
  STRING_AGG(distinct name, ', ' ORDER BY name) names,
  STRING_AGG(
    DISTINCT (
      CASE WHEN something = true THEN 'type1'
           WHEN something_else = true THEN 'type2'
           ELSE 'type3'
      END
    ) as types, ', ' ORDER BY types) types
  from organisations
  </code></pre>