问题
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