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

标签 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(整数)对于每个记录都是唯一的,而每个变量a有24列(数字)bc 因此总计为 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);

使用executeanonymous 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/

相关文章:

php - 如何为我的应用程序创建索引数据库

c# - 添加新记录时,Visual Studio SQL 默认值未显示在 Windows 窗体上

mysql - 1305 - 程序 db.delete_catelog_item 不存在

json - Postgresql - 更新 JSONB 列类型的 SQL

sql - 查询以在特定条件下重置以递增计数

2 组 SQL 查询

java - ROW_NUMBER() 没有正确排序记录

ruby-on-rails - Heroku - ActiveRecord::ConnectionTimeoutError(无法在 5.000 秒内获得数据库连接(等待 5.000 秒))

sql - 哪个查询计划更快/更好

sql - 错误: could not create unique index DETAIL: Key (id)=(3105115) is duplicated