10

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?

Steinthor.palsson
  • 6,286
  • 13
  • 44
  • 51

2 Answers2

29

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

mu is too short
  • 426,620
  • 70
  • 833
  • 800
user470714
  • 2,858
  • 1
  • 28
  • 34
4
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:

SELECT a, sum(b)
FROM sample_data
GROUP BY a
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95