postgresql 计算结果集的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7376072/
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
postgresql calculate sum of a resultset
提问by Steinthor.palsson
Is there any built in function in postgresql to get the sum of of a column.
postgresql 中是否有任何内置函数来获取列的总和。
Just a simple example
只是一个简单的例子
CREATE TABLE sample_table (a INTEGER, b REAL);
INSERT INTO sample_table (a, b) VALUES (5, 7.22);
INSERT INTO sample_table (a, b) VALUES (5, 5.6);
INSERT INTO sample_table (a, b) VALUES (1, 23.5);
INSERT INTO sample_table (a, b) VALUES (1, 2.2)
Now lets say I want to get the sum of all the values of 'b' where a = 5
How would I do that?
现在让我们说我想得到 'b' 的所有值的总和,其中 a = 5
我该怎么做?
回答by user470714
I think it would just be
我想这只是
SELECT SUM(b) FROM sample_table WHERE a = 5;
You can learn about all the Postgres aggregate function here:
您可以在此处了解所有 Postgres 聚合函数:
http://www.postgresql.org/docs/current/static/functions-aggregate.html
http://www.postgresql.org/docs/current/static/functions-aggregate.html
回答by Petar Ivanov
SELECT sum(b)
FROM sample_data
WHERE a = 5
You can also use group by to get a list of different values for a together with the sums of b corresponding to each of a:
您还可以使用 group by 来获取 a 的不同值列表以及与每个 a 对应的 b 的总和:
SELECT a, sum(b)
FROM sample_data
GROUP BY a