Postgres:选择值的总和,然后再次求和

时间:2012-08-22 10:10:22

标签: postgresql select sum

我尝试了很多但却找不到正确的方法。 如果我在Postgres中选择值并对它们求和,它看起来像这样:

SELECT name,sum(size) as total
FROM mytable group by name order by name;

如何改变这一点,以便总计所有值?我想我需要一个子选择但是如何?

4 个答案:

答案 0 :(得分:19)

试试这个:

SELECT sum(a.total)
FROM (SELECT sum(size) as total
      FROM mytable group by name) a

<强>更新 对不起,我没有在同一个查询中读到你想要的一切。出于这个原因, greg 的答案会更好。但是,如果你有一个postgresql版本&gt; = 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

答案 1 :(得分:3)

这应该对你有帮助:

select sum(innerselect.innertotal) as outertotal from 
    (select sum(size) as innertotal from mytable group by name) as innerselect

答案 2 :(得分:3)

如果您希望所有结果具有相同的SELECT,则可以执行类似

的操作
SELECT 
  'grand total' AS name, 
   sum(size) AS sum 
FROM 
  mytable 
UNION ALL 
SELECT 
  name, 
  sum(size) AS sum 
FROM 
  mytable 
GROUP BY 
  name;

希望它有所帮助...

答案 3 :(得分:2)

我将在POSTRGESQL上使用ROLLUP函数:

SELECT name,sum(size) as total
FROM mytable 
group by ROLLUP(name )
order by name;

这将为您提供您汇总的所有值的总计,还可以用于汇总多个列。

希望有帮助!