![](/img/trans.png)
[英]sql loop with id, date, and 1 additional field (in redshift)
[英]SQL adding new column as arbitrary calculated field (Postgres / redshift)
我正在尝试将新的计算字段(列)添加到表中。
如果将 python 与 pandas 一起使用,我可以这样做:
df['new_field'] = df[['col1', 'col2']].apply(func, axis=1)
假设func
在 SQL 中被定义为一个 UDF,它返回一个 bool,我如何通过将它应用到我表中的其他列来创建一个新列? 我尝试了这个但没有成功:
alter table my_table
add column new_field bool default null;
update my_table set new_field = (select func(col1, col2) from my_table);
这是错误的,因为更新需要单个值或 where 子句。 我也曾尝试将计算字段存储在新表中,但我没有用于合并它们的公共键,因此排序顺序会变得混乱。
现在我能想到的最好的解决方案是
create table my_table_2 as (select *, func(col1, col2) as new_field from table);
但这似乎效率不高。
你会称它为:
update my_table
set new_field = func(col1, col2) ;
不需要额外的select
,除非它恰好是一个聚合函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.