16

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

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

我怎样才能改变这个,所以它也总和所有的值?我想我需要一个子选择,但如何?

4

4 回答 4

35

试试这个:

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

更新 对不起,我没有读到您希望在同一个查询中全部完成。出于这个原因,格雷格的答案更好。但是,如果您的 postgresql 版本 >= 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
于 2012-08-22T10:20:25.727 回答
9

我会在 POSTRGESQL 上使用 ROLLUP 函数:

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

这将为您提供聚合的任何值的总计,也可用于聚合多个列。

希望能帮助到你!

于 2019-02-27T19:33:06.010 回答
4

如果您希望所有结果都具有相同的 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;

希望对您有所帮助……</p>

于 2012-08-22T11:37:56.370 回答
3

那么这应该可以帮助你:

select sum(innerselect.innertotal) as outertotal from 
    (select sum(size) as innertotal from mytable group by name) as innerselect
于 2012-08-22T10:20:42.270 回答