Create a function with multiple columns as arguments in Postgresql

I am trying to create a function that takes a table and a variable number of columns as arguments, and then returns a table without rows that have duplicates in all of these columns. I am trying to figure out how to have a variable number of columns as arguments, and I realized that I would probably need an argument VARIADIC, but I'm not sure how to implement it. What I still have:

CREATE FUNCTION remove_duplicates(orig_table, VARIADIC sel_columns column)
RETURNS table AS $$
    SELECT * FROM 
        (SELECT *,
            count(*) over (partition by sel_columns) AS count
        FROM orig_table)
    WHERE count = 1;
$$ LANGUAGE SQL;

As an example, if I had a table like this:

cola | colb | colc
-------------------
a    | b    | 1
a    | b    | 2
a    | c    | 3
a    | d    | 4

I would like to run SELECT * FROM remove_duplicates(mytable, cola, colb)and get this result:

cola | colb | colc
-------------------
a    | c    | 3
a    | d    | 4

Thanks for the help. I am using postgresql 9.4.9

+4
source share
1

, , SQL, . :

CREATE OR REPLACE FUNCTION remove_duplicates(orig_table anyelement, VARIADIC sel_columns text[])
RETURNS SETOF anyelement AS $$
DECLARE
    orig_table_columns TEXT;
BEGIN
    SELECT array_to_string(array_agg(quote_ident(column_name)),',') INTO orig_table_columns FROM information_schema.columns WHERE table_name = CAST(pg_typeof(orig_table) AS TEXT);
    RETURN QUERY EXECUTE 'SELECT ' || orig_table_columns || ' FROM '
        || '(SELECT *, '
        || '    count(*) over (partition by ' || array_to_string(sel_columns, ',') || ') AS count '
        || 'FROM ' || pg_typeof(orig_table) || ') AS tmp '
        || ' WHERE count = 1 ';
END
$$ LANGUAGE PLPGSQL;

SELECT * FROM remove_duplicates(NULL::tests, 'cola', 'colb');

, SQL.

EDIT: . Erwin answer .

+1

Source: https://habr.com/ru/post/1677273/


All Articles