postgresql calculate sum of a resultset

Steinthor.palsson picture Steinthor.palsson · Sep 11, 2011 · Viewed 44.6k times · Source

Is there any built in function in postgresql to get the sum of of a column.

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?

Answer

user470714 picture user470714 · Sep 11, 2011

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:

http://www.postgresql.org/docs/current/static/functions-aggregate.html