2017-08-27 27 views
1

好的,我的问题类似于this但我的情况是不同的。在我的PostgreSQL 9.5数据库,我也有布局表格my_table类似如下:PostgreSQL:如何将多列中的每个条目乘以固定数字?

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 (integer)是每个记录独特而有24列(numeric)每个变量abc这样总结到72列。我想把这72列中的每个条目乘以一个固定的数字,比如0.20。我知道的PostgreSQL UPDATE命令是这样的:

UPDATE my_table set a0 = a0 * 0.20 

在这种情况下,我需要重复这个命令了大量的时间(不需要)。有没有其他快速方法(单个SELECT或迭代)将固定数字乘以多列?

回答

1

示例表:

使用executeanonymous code block

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); 

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) 
+0

谢谢!你是一个拯救生命的人:) –

相关问题