Search code examples
postgresqlselectsum

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?


Solution

  • 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