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.
My intention is to
Select an element from a json array called
pickupLocations
. There are manypickupLocations
for everyid_referral
. See the CTE namedraw_addresses
below., andUse a string aggregation function (e.g.
string_agg
) to create a delimited field of addresses for eachid_referral
.
In other words, I want to be able to go from
#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
in my raw_addresses
CTE
to
#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
in my final select.
However, I am now getting the following results
#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
When using the code below.
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") -> '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
For some reason, the string_agg
function is repeating the first value for each id_referral
. I have also tried agg_array
and get the same behavior.
Any thoughts as to why would be much appreciated.