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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With