Is there a way to find the sum of each row? postgresql

删除回忆录丶 提交于 2021-02-11 13:51:15

问题


Let's say you have a table of n columns like

  create table x
     (id integer
      x0 integer,
      x1 integer,
      x2 integer,
      x3 integer,
      .....
      xn integer
      primary key(id)
      )

n can be a big number, also you don't know the names of the columns. Let's say you have 50 rows like

insert into x (74934,1, 9, 21, 5....16)
insert into x (58496,4, 2, 3, 19....52)
.....
insert into x (10475,48, 245, 8, 71....111)

Is there a way to find the sum of each row? Like 1 + 9 + 21 + 5 +...+ 16 = sum of first row


回答1:


Using JSON(B) functions:

with t(id, x1, x2, x3) as (values(1,1,2,3),(2,4,5,6))
select
    id,
    (select sum(value::numeric) from jsonb_each(to_jsonb(t)) where key like 'x%')
from t;


来源:https://stackoverflow.com/questions/61393659/is-there-a-way-to-find-the-sum-of-each-row-postgresql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!