簡體   English   中英

postgres - 聚合文本數組中的項目

[英]postgres - aggregate items in text array

我有一個文本項數組,數組中的每個文本項都是一個分隔字符串,這里是一個示例:

drop table if exists tmp;
create table tmp(x text);
insert into tmp select ('1~41.5~50~1|2~43.72~1000~1|3~52.0~1~1|4~57.5~7500~1|5~68.0~8~1|6~80.95~6~1|7~84.25~300~1');

with t as (
    select string_to_array(x , '|') arr 
    from  tmp
)
select * , cardinality(arr) arr_len , split_part(arr[1],'~',2)
from t

示例輸出:

"{1~41.5~50~1,2~43.72~1000~1,3~52.0~1~1,4~57.5~7500~1,5~68.0~8~1,6~80.95~6~1,7~84.25~300~1}";7;"41.5"

我對提取價格感興趣,它表示為每個數組條目的第二項(當以 ~ 分隔時),因此輸出將是:

41.5,43.72,52.0,...

使用split_partsplit_part返回特定數組索引的一個結果,我不想硬編碼所有索引,因為它會有所不同。

建議表示贊賞。

這是一種方法:

select t.*, w.prices
from tmp t
cross join lateral (
    select array_agg(split_part(v.z, '~', 2)) prices
    from regexp_split_to_table(t.x, '\|') as v(z)
) w

在子查詢中,我們使用分隔符|將字符串拆分為行| ; 然后,我們將每一行的第二個元素聚合回一個數組。

你可以明確的是要保持與元素的順序with ordinality

select t.*, w.prices
from tmp t
cross join lateral (
    select array_agg(split_part(v.z, '~', 2) order by v.n) prices
    from regexp_split_to_table(t.x, '\|') with ordinality as v(z, n)
) w

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM