如果下面的一些代码是多余的,我很抱歉,但我想描绘一下我想要做的一切。
我的意图是
从名为pickupLocations
的json数组中选择一个元素。每pickupLocations
有许多id_referral
。 请参阅下面名为raw_addresses
的CTE。和
使用字符串聚合函数(例如string_agg
)为每个id_referral
创建一个分隔的地址字段。
换句话说,我希望能够从
开始#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
在我的raw_addresses
CTE
到
#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
在我的最终选择中。
但是,我现在得到以下结果
#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
使用以下代码时。
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
出于某种原因,string_agg
函数正在重复每个id_referral
的第一个值。我也尝试了agg_array
并获得相同的行为。
任何关于为什么会被赞赏的想法。
答案 0 :(得分:0)
您可以尝试使用中间CTE:
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
), transformed_addresses AS (
SELECT id_referral,
cast(pickup_address as varchar(100)) AS pickup_address
FROM raw_addresses
)
SELECT id_referral,
string_agg(pickup_address, '|') AS pickup_addresses
FROM transformed_addresses
GROUP BY id_referral