eliminate duplicate array values in postgres

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

    Here's the "inline" way:

    SELECT 1 AS anycolumn, (
      SELECT array_agg(c1)
      FROM (
        SELECT DISTINCT c1
        FROM (
          SELECT unnest(ARRAY[1234,5343,6353,1234,1234]) AS c1
        ) AS t1
      ) AS t2
    ) AS the_array;
    

    First we create a set from array, then we select only distinct entries, and then aggregate it back into array.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题