How to get distinct array elements with postgres?

送分小仙女□ 提交于 2019-12-01 07:21:27

问题


I have an array with duplicate values in postgres. For example:

SELECT cardinality(string_to_array('1,2,3,4,4', ',')::int[]) as foo
=> "foo"=>"5"

I would like to get unique elements, for example:

SELECT cardinality(uniq(string_to_array('1,2,3,4,4', ',')::int[])) as foo
=> -- No function matches the given name and argument types. You might need to add explicit type casts.

Can I get unique elements of an array in postgres without using UNNEST ?


回答1:


For integer arrays use intarray extension:

create extension if not exists intarray;
SELECT cardinality(uniq(string_to_array('1,2,3,4,4', ',')::int[])) as foo

or the function

create or replace function public.array_unique(arr anyarray)
    returns anyarray
    language sql
as $function$
    select array_agg(distinct a)
    from (
        select unnest(arr) a 
    ) alias
$function$;

for any array.




回答2:


I prefer this syntax (about 5% faster)

create or replace function public.array_unique(arr anyarray)
returns anyarray as $body$
    select array( select distinct unnest($1) )
$body$ language 'sql';

using:

select array_unique(ARRAY['1','2','3','4','4']);



回答3:


Going off of @klin's accepted answer, I modified it to remove nulls in the process of choosing only the distinct values.

create or replace function public.array_unique_no_nulls(arr anyarray)
returns anyarray
language sql
as $function$
select array_agg(distinct a)
from (
    select unnest(arr) a 
) alias
where a is not null
$function$;


来源:https://stackoverflow.com/questions/40636406/how-to-get-distinct-array-elements-with-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!