Postgres:选择值的总和,然后再次求和 [英] Postgres: select the sum of values and then sum this again

查看:90
本文介绍了Postgres:选择值的总和,然后再次求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

尝试一下:

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

更新
很抱歉,我没有读过您想要的所有内容相同的查询。因此, greg 的答案会更好。但是,如果您的Postgresql版本> = 9,还有另一种可能性:

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

这篇关于Postgres:选择值的总和,然后再次求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆