gpt4 book ai didi

sql - POSTGRESQL:创建表作为选择特定类型的列

转载 作者:行者123 更新时间:2023-11-29 13:32:34 25 4
gpt4 key购买 nike

我有一个包含混合类型数据(实数、整数、字符...)的表,但我只会恢复具有实数值的列。

我可以构造这个:

SELECT 'SELECT ' || array_to_string(ARRAY(
select 'o' || '.' || c.column_name
from information_schema.columns as c
where table_name = 'final_datas'
and c.data_type = 'real'), ',') || ' FROM final_datas as o' As sqlstmt

这给出了:

"SELECT o.random,o.struct2d_pred2_num,o.pfam_num,o.transmb_num [...] FROM final_datas as o"

我想用这些列创建一个表。当然,这样做是行不通的:

create table table2 as (
SELECT 'SELECT ' || array_to_string(ARRAY(
select 'o' || '.' || c.column_name
from information_schema.columns as c
where table_name = 'final_datas'
and c.data_type = 'real'), ',') || ' FROM final_datas as o' As sqlstmt
)

建议?

最佳答案

您需要将整个 CREATE TABLE 语句生成为动态 SQL:

SELECT 'CREATE TABLE table2 AS SELECT ' || array_to_string(ARRAY(
select 'o' || '.' || c.column_name
from information_schema.columns as c
where table_name = 'final_datas'
and c.data_type = 'real'), ',') || ' FROM final_datas as o' As sqlstmt

结果可以用EXECUTE sqlstmt;运行

关于sql - POSTGRESQL:创建表作为选择特定类型的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20179466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com