第一个结果在postgres中的array_agg和string_agg函数中重复

时间:2016-05-25 21:25:28

标签: sql arrays json postgresql

如果下面的一些代码是多余的,我很抱歉,但我想描绘一下我想要做的一切。

我的意图是

  1. 从名为pickupLocations的json数组中选择一个元素。每pickupLocations有许多id_referral请参阅下面名为raw_addresses的CTE。

  2. 使用字符串聚合函数(例如string_agg)为每个id_referral创建一个分隔的地址字段。

  3. 换句话说,我希望能够从

    开始
    #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并获得相同的行为。

    任何关于为什么会被赞赏的想法。

1 个答案:

答案 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