PostgreSQL:如何将多列中的每个条目乘以固定数字?

时间:2017-08-27 15:02:01

标签: sql postgresql

好的,我的问题与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 (integer)对于每条记录都是唯一的,而每个变量(numeric)ab共有24列c,因此总计为72列。我想将这72列中的每个条目乘以一个固定的数字,比方说0.20。我知道这样的PostgreSQL UPDATE命令:

UPDATE my_table set a0 = a0 * 0.20

在这种情况下,我需要重复此命令很多次(不需要的)。是否有另一种快速方法(单SELECT或迭代)将固定数字乘以多列?

1 个答案:

答案 0 :(得分:1)

示例表:

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) 
相关问题