我想创建一个表,其中每一列都是从选择查询中检索到的不同值。
例子:
[查询]
SELECT DISTINCT col
FROM table
[结果]
col
---
val1
val2
val3
val4
请求的表:
Column1 | Column2 | Column3 | ... | ColumnN
-------------------------------------------
val1 | val2 | val3 | ... | valN
存在未知数量的不同值。所有列都应创建为 TEXT 类型。
这是否可以在没有过程的情况下使用 SQL?
谢谢。
最佳答案
你必须使用 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 | | |
关于sql - 创建表,其中每一列都是从选择查询中检索到的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52816052/