postgresql calculate sum of a resultset
Is there any built in function in postgresql to get the sum of of开发者_Go百科 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?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
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
精彩评论