How to get distinct array elements with postgres?

后端 未结 3 691
忘掉有多难
忘掉有多难 2021-01-14 00:23

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         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 00:46

    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$;
    

提交回复
热议问题