好的,我的问题类似于this但我的情况不同。在我的 PostgreSQL 9.5 数据库中,我有一个表 my_table
,其布局如下:
ID a0 a1 .. a23 b0 b1 .. b23 c0 c1 .. c23
1 23 22 .. 11 12 0.12 .. 65 0.17 12 .. 19
2 42 52 .. 12 1.2 14 .. 42 0.35 12 .. 12
3 11 25 .. 13 2.5 0.14 .. 15 1.1 8 .. 14
第一列ID(整数)
对于每个记录都是唯一的,而每个变量a
有24列(数字)
,b
和 c
因此总计为 72 列。我想将这 72 列中的每个条目乘以一个固定数字,比如 0.20。我知道 PostgreSQL UPDATE
命令是这样的:
UPDATE my_table set a0 = a0 * 0.20
在这种情况下,我需要多次重复此命令(不需要)。是否有替代的快速方法(单个 SELECT
或迭代)将固定数字乘以多列?
最佳答案
示例表:
drop table if exists my_table;
create table my_table(id serial primary key, a1 dec, a2 dec, a3 dec);
insert into my_table values
(default, 1, 2, 3);
使用execute在anonymous code block :
do $$
begin
execute concat('update my_table set ', string_agg(format('%1$I = %1$I * 0.2', attname), ','))
from pg_attribute a
where attrelid = 'my_table'::regclass
and attnum > 0
and attname ~ '^[abc]+';
end
$$;
select * from my_table;
id | a1 | a2 | a3
----+-----+-----+-----
1 | 0.2 | 0.4 | 0.6
(1 row)
关于sql - PostgreSQL:如何将多列中的每个条目乘以固定数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45906335/