How to compute the sum of multiple columns in PostgreSQL

后端 未结 3 683
情深已故
情深已故 2020-12-24 01:29

I would like to know if there\'s a way to compute the sum of multiple columns in PostgreSQL.

I have a table with more than 80 columns and I have to write a query th

相关标签:
3条回答
  • 2020-12-24 01:41

    Combined the current answers and used this to get total SUM:

    SELECT SUM(COALESCE(col1,0) + COALESCE(col2,0)) FROM yourtable;
    
    0 讨论(0)
  • 2020-12-24 01:49

    It depends on how you'd like to sum the values. If I read your question correctly, you are looking for the second SELECT from this example:

    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=# 
    
    0 讨论(0)
  • 2020-12-24 01:52
    SELECT COALESCE(col1,0) + COALESCE(col2,0)
    FROM yourtable
    
    0 讨论(0)
提交回复
热议问题