Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres: select the sum of values and then sum this again

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?

like image 801
Anatol Avatar asked Aug 22 '12 10:08

Anatol


People also ask

How do I sum query 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 create a sum function in PostgreSQL?

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.

How do I do an aggregate sum in SQL?

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.

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.


1 Answers

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
like image 54
doctore Avatar answered Sep 19 '22 23:09

doctore