如何计算PostgreSQL中多列的总和

Psy*_*che 32 postgresql

我想知道是否有办法计算PostgreSQL中多列的总和.

我有一个包含80多列的表,我必须编写一个查询来添加每列的每个值.

我尝试使用SUM(col1,col2,col3等),但它没有用.

qqx*_*qqx 56

SELECT COALESCE(col1,0) + COALESCE(col2,0)
FROM yourtable
Run Code Online (Sandbox Code Playgroud)


Dan*_*rey 43

这取决于你如何总结这些值.如果我正确地阅读了您的问题,那么您正在寻找此示例中的第二个SELECT:

template1=# SELECT * FROM yourtable ;
 a | b 
---+---
 1 | 2
 4 | 5
(2 rows)

template1=# SELECT a + b FROM yourtable ;
 ?column? 
----------
        3
        9
(2 rows)

template1=# SELECT SUM( a ), SUM( b ) FROM yourtable ;
 sum | sum 
-----+-----
   5 |   7
(1 row)

template1=# SELECT SUM( a + b ) FROM yourtable ;
 sum 
-----
  12
(1 row)

template1=# 
Run Code Online (Sandbox Code Playgroud)


And*_*rew 10

结合当前答案并使用它来获得总和:

SELECT SUM(COALESCE(col1,0) + COALESCE(col2,0)) FROM yourtable;
Run Code Online (Sandbox Code Playgroud)