Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql calculate sum of a resultset

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?

like image 440
Steinthor.palsson Avatar asked Sep 11 '11 03:09

Steinthor.palsson


People also ask

How do I sum values in PostgreSQL?

Summary. Use the SUM() function to calculate the sum of values. Use the DISTINCT option to calculate the sum of distinct values. Use the SUM() function with the GROUP BY clause to calculate the sum for each group.

How do I do a cumulative sum in PostgreSQL?

Basically, you need a window function. That's a standard feature nowadays. In addition to genuine window functions, you can use any aggregate function as window function in Postgres by appending an OVER clause.

How do I count unique values in PostgreSQL?

In this form, the COUNT(DISTINCT column) returns the number of unique non-null values in the column. We often use the COUNT() function with the GROUP BY clause to return the number of items for each group. For example, we can use the COUNT() with the GROUP BY clause to return the number of films in each film category.

What is rollup in PostgreSQL?

The PostgreSQL ROLLUP belongs to the GROUP BY clause that provides a short cut for defining multiple grouping sets. Multiple columns grouped together forms a group set. Unlike the CUBE subclause, ROLLUP does not yield all possible grouping sets based on the specified columns. It just makes a subset of those.


2 Answers

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

like image 104
user470714 Avatar answered Oct 14 '22 03:10

user470714


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
like image 34
Petar Ivanov Avatar answered Oct 14 '22 01:10

Petar Ivanov