I tried a lot but can´t find the right way. If I select values in Postgres and sum them it looks like this:
SELECT name,sum(size) as total
FROM mytable group by name order by name;
How can I alter this so it also sum all values in total? I think I need a subselect but how?
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.
PostgreSQL SUM function is used to find out the sum of a field in various records. You can take the sum of various records set using the GROUP BY clause. The following example will sum up all the records related to a single person and you will have salary for each person.
The SQL Server SUM() function is an aggregate function that calculates the sum of all or distinct values in an expression. In this syntax: ALL instructs the SUM() function to return the sum of all values including duplicates. ALL is used by default.
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.
Try this:
SELECT sum(a.total)
FROM (SELECT sum(size) as total
FROM mytable group by name) a
UPDATE I'm sorry, I don't read that you want it all in the same query. For this reason the answer of greg it's better. However, other possibility if you have a postgresql version >= 9:
WITH mytableWith (name, sum) as
(SELECT name, sum(size)
FROM mytable
GROUP BY name)
SELECT 'grand total' AS name,
sum(sum) AS sum
FROM mytableWith
UNION ALL
SELECT name, sum
FROM mytableWith
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