创建表,其中每个列都是从选择查询中检索到的不同值

时间:2018-10-15 11:44:45

标签: sql postgresql

我想创建一个表,其中每个列都是从选择查询中检索到的不同值。

示例:

[查询]

SELECT DISTINCT col 
FROM table

[结果]

col
 --- 
val1
val2
val3
val4

请求的表:

Column1 | Column2 | Column3 | ... | ColumnN
-------------------------------------------
 val1   |  val2   |  val3   | ... | valN 

未知数量的不同值。所有列均应创建为TEXT类型。

使用不带过程的SQL是否可能?

谢谢。

1 个答案:

答案 0 :(得分:0)

您必须使用dynamic command。如果不想创建函数,请使用匿名代码块,例如:

create table table_cols(col text);
insert into table_cols values
('col1'), 
('col2'),
('col3');

do $$
begin
    execute format('create table new_table(%s text)', string_agg(distinct col, ' text, '))
    from table_cols;
end
$$

检查:

\d new_table

            Table "public.new_table"
 Column | Type | Collation | Nullable | Default 
--------+------+-----------+----------+---------
 col1   | text |           |          | 
 col2   | text |           |          | 
 col3   | text |           |          |