如何拆分使用array_agg

时间:2017-09-12 17:31:14

标签: postgresql

我试图拆分使用array_agg创建的阵列列。以下是严重削减,原始查询类似于210行

select 
 distinct on (visitor.id)
 id,
 array_agg(distinct item.code::text)

from
 8xfullouter joins

where
exists(
select
distinct on(visitor.id)
item.code::text
from
3 full outer join that all appear in the first query

group by
visit.id, 
item.code

order by 
visit.id
)

我需要将array_agg(distinct item.code :: text)分成多个列。我已经尝试过split_part(array_agg(distinct item.code :: text),',',1)但是收到了以下内容

> [Err] ERROR:  function split_part(character varying[], unknown,
> integer) does not exist LINE 159: split_part (array_agg(distinct
> "public".procedure_group_cpt_...

感谢!!!

1 个答案:

答案 0 :(得分:1)

使用数组的索引,例如:

select (array_agg(code::text))[1] 
from (values ('code1'), ('code2')) as codes(code)

 array_agg 
-----------
 code1
(1 row)

或者,您可以使用string_agg()代替array_agg(),例如:

select split_part(string_agg(code::text, ','), ',', 1)
from (values ('code1'), ('code2')) as codes(code)

 split_part 
------------
 code1
(1 row)