拆分文本字符串并使其成为 Postgres 中的聚合列表

Split Text string and make it a aggregated list in Postgres

我的 PostgreSQL table 中有 2 列,如下所示,客户 ID 标签值。我想获取所有标签的名称值,用逗号分隔。我该怎么做。

输入

Customer_ID_343        [{"tagId": "W", "name": "ds_initialsegment04", "href": "https://api3.getresponse360.pl/v3/tags/W", "color": ""}
    , {"tagId": "I", "name": "rea", "href": "https://api3.getresponse360.pl/v3/tags/I", "color": ""}
    , {"tagId": "c", "name": "rea_gen0220_7mbis10m", "href": "https://api3.getresponse360.pl/v3/tags/c", "color": ""}
    , {"tagId": "o", "name": "rea_20200220_gen", "href": "https://api3.getresponse360.pl/v3/tags/o", "color": ""}
    , {"tagId": "5", "name": "no_wholesale_order_greater_0", "href": "https://api3.getresponse360.pl/v3/tags/5", "color": ""}
    , {"tagId": "B", "name": "H0710gen", "href": "https://api3.getresponse360.pl/v3/tags/B", "color": ""}]

预期产出

Customer_ID_343  ds_initialsegment04,rea,rea_gen0220_7mbis10m,rea_20200220_gen,no_wholesale_order_greater_0,H0710gen

您似乎有 json 数据。如果是这样,您可以使用 json[b]_array_elements() 取消嵌套数组元素,然后使用字符串聚合。横向连接可以方便地处理逻辑:

select t.customer_id, x.names
from mytable t
cross join lateral (
    select string_agg(x.obj ->> 'name', ',') as names
    from jsonb_array_elements(t.tags) as x(obj)
) x