postgresql 如何计算PostgreSQL中多列的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15719557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compute the sum of multiple columns in PostgreSQL
提问by Psyche
I would like to know if there's a way to compute the sum of multiple columns in PostgreSQL.
我想知道是否有一种方法可以计算 PostgreSQL 中多列的总和。
I have a table with more than 80 columns and I have to write a query that adds each value from each column.
我有一个包含 80 多列的表,我必须编写一个查询来添加每列中的每个值。
I tried with SUM(col1, col2, col3 etc) but it didn't work.
我尝试使用 SUM(col1, col2, col3 etc) 但它没有用。
回答by qqx
SELECT COALESCE(col1,0) + COALESCE(col2,0)
FROM yourtable
回答by Daniel Frey
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:
这取决于您希望如何对值求和。如果我正确阅读了您的问题,那么您正在寻找此示例中的第二个 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=#
回答by Andrew
Combined the current answers and used this to get total SUM:
结合当前的答案并使用它来获得总和:
SELECT SUM(COALESCE(col1,0) + COALESCE(col2,0)) FROM yourtable;