0
4

1 回答 1

1

基本上,您不能从表中选择未知列。查询结果在执行之前必须具有定义的结构。您可以做的是创建一个包含预期列的(临时)视图。下面的函数完成了这项工作,广泛使用动态 SQL。该函数的第一个参数是表名,第二个参数是要创建的临时视图的名称。

create or replace function create_view_with_distinct_columns(text, text)
returns void language plpgsql as $$
declare
    col text;
    ct int;
    list text = '';
begin
    for col in 
        execute format('
            select attname
            from pg_attribute
            where attrelid = %s
            and attnum > 0',
            $1::regclass::oid)
    loop
        execute format('
            select count(distinct %I)
            from %I',
            col, $1)
        into ct;
        if ct > 1 then
            list:= format('%s%s,', list, col);
        end if;
    end loop;
    execute format('
        create temp view %I as
        select %s
        from %I',
        $2, left(list, -1), $1);
end $$;

利用:

select create_view_with_distinct_columns('column_test', 'column_view');

select * from column_view;

     foo     | bar
-------------+-----
 lorem ipsum |   1
 lorem ipsum |   2
 other       |   3
(3 rows)    

Db<>小提琴。

于 2020-05-04T14:31:59.227 回答