eliminate duplicate array values in postgres

后端 未结 8 1098
孤独总比滥情好
孤独总比滥情好 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:50

    Using DISTINCT implicitly sorts the array. If the relative order of the array elements needs to be preserved while removing duplicates, the function can be designed like the following: (should work from 9.4 onwards)

    CREATE OR REPLACE FUNCTION array_uniq_stable(anyarray) RETURNS anyarray AS
    $body$
    SELECT
        array_agg(distinct_value ORDER BY first_index)
    FROM 
        (SELECT
            value AS distinct_value, 
            min(index) AS first_index 
        FROM 
            unnest($1) WITH ORDINALITY AS input(value, index)
        GROUP BY
            value
        ) AS unique_input
    ;
    $body$
    LANGUAGE 'sql' IMMUTABLE STRICT;
    

提交回复
热议问题