eliminate duplicate array values in postgres

后端 未结 8 1100
孤独总比滥情好
孤独总比滥情好 2020-12-01 01:27

I have an array of type bigint, how can I remove the duplicate values in that array?

Ex: array[1234, 5343, 6353, 1234, 1234]

I shou

8条回答
  •  醉话见心
    2020-12-01 01:35

    For people like me who still have to deal with postgres 8.2, this recursive function can eliminate duplicates without altering the sorting of the array

    CREATE OR REPLACE FUNCTION my_array_uniq(bigint[])
      RETURNS bigint[] AS
    $BODY$
    DECLARE
        n integer;
    BEGIN
    
        -- number of elements in the array
        n = replace(split_part(array_dims($1),':',2),']','')::int;
    
        IF n > 1 THEN
            -- test if the last item belongs to the rest of the array
            IF ($1)[1:n-1] @> ($1)[n:n] THEN
                -- returns the result of the same function on the rest of the array
                return my_array_uniq($1[1:n-1]);
            ELSE
                -- returns the result of the same function on the rest of the array plus the last element               
                return my_array_uniq($1[1:n-1]) || $1[n:n];
            END IF;
        ELSE
            -- if array has only one item, returns the array
            return $1;
        END IF;
    END;
    $BODY$
      LANGUAGE 'plpgsql' VOLATILE;
    

    for exemple :

    select my_array_uniq(array[3,3,8,2,6,6,2,3,4,1,1,6,2,2,3,99]);
    

    will give

    {3,8,2,6,4,1,99}
    

提交回复
热议问题