title: First result repeating in array_agg and string_agg functions in postgres
body: <p>I apologize if some of the code below is superfluous, but I am wanting to paint a picture of everything I am trying to do. </p>
  
  <p>My intention is to </p>
  
  <ol>
  <li><p>Select an element from a json array called <code>pickupLocations</code>. There are many <code>pickupLocations</code> for every <code>id_referral</code>. <em>See the CTE named <code>raw_addresses</code> below.</em>, and  </p></li>
  <li><p>Use a string aggregation function (e.g. <code>string_agg</code>) to create a delimited field of addresses for each <code>id_referral</code>. </p></li>
  </ol>
  
  <p>In other words, I want to be able to go from </p>
  
  <pre><code>#id_referral    pickup_addresses
  #1  4265 Hillsdale Ave. NE, Grand Rapids, MI 49525
  #1  3060 Cheney Ave. NE, Grand Rapids, MI 49525
  #2  805 Kendalwood St. NE, Grand Rapids, MI 49505
  #2  711 Edgewood St. NE, Grand Rapids, MI 49505
  </code></pre>
  
  <p>in my <code>raw_addresses</code> CTE</p>
  
  <p>to </p>
  
  <pre><code>#id_referral    pickup_addresses
  #1  4265 Hillsdale Ave. NE, Grand Rapids, MI 49525 | 3060 Cheney Ave. NE, Grand Rapids, MI 49525
  #2  805 Kendalwood St. NE, Grand Rapids, MI 49505 | 711 Edgewood St. NE, Grand Rapids, MI 49505
  </code></pre>
  
  <p>in my final select. </p>
  
  <p>However, I am now getting the following results </p>
  
  <pre><code>#id_referral    pickup_addresses
  #1  4265 Hillsdale Ave. NE, Grand Rapids, MI 49525 | 4265 Hillsdale Ave. NE, Grand Rapids, MI 49525
  #2  805 Kendalwood St. NE, Grand Rapids, MI 49505 | 805 Kendalwood St. NE, Grand Rapids, MI 49505
  </code></pre>
  
  <p>When using the code below. </p>
  
  <pre><code> WITH raw_addresses AS (
           SELECT sr.id AS id_referral,
          --parsing a json array which has many pickupLocations for a single id_referral
              json_array_elements(sr."pickupLocations") -&gt; 'pickupLocationAddress' AS pickup_address
             FROM "ServiceReferrals" sr
          )
  --want to roll the pickup addresses into a single pipe-delimited field (willing work through an array too as shown with array_agg, but same problem there)
   SELECT raw_addresses.id_referral,
      string_agg(cast(pickup_address as varchar(100)), '|') AS pickup_addresses
     FROM raw_addresses
    GROUP BY raw_addresses.id_referral
  </code></pre>
  
  <p>For some reason, the <code>string_agg</code> function is repeating the first value for each <code>id_referral</code>. I have also tried <code>agg_array</code> and get the same behavior. </p>
  
  <p>Any thoughts as to why would be much appreciated. </p>