postgresql Postgres:选择值的总和,然后再次求和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12070855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Postgres: select the sum of values and then sum this again
提问by t Book
I tried a lot but can′t find the right way. If I select values in Postgres and sum them it looks like this:
我尝试了很多,但找不到正确的方法。如果我在 Postgres 中选择值并将它们相加,它看起来像这样:
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?
我怎样才能改变它,以便它也总和所有值?我想我需要一个子选择,但如何?
回答by doctore
Try this:
尝试这个:
SELECT sum(a.total)
FROM (SELECT sum(size) as total
FROM mytable group by name) a
UPDATEI'm sorry, I don't read that you want it all in the same query. For this reason the answer of gregit's better. However, other possibility if you have a postgresql version >= 9:
更新对不起,我没有读到您希望在同一个查询中全部使用。出于这个原因,greg的答案更好。但是,如果您的 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
回答by greg
If you want all results with the same SELECT, you could do something like
如果您希望所有结果都具有相同的 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;
Hope it helps…
希望能帮助到你…
回答by oyeoyeoye
I would use the ROLLUP function on POSTRGESQL:
我会在 POSTRGESQL 上使用 ROLLUP 函数:
SELECT name,sum(size) as total
FROM mytable
group by ROLLUP(name )
order by name;
This will give you a grand total of any value that you aggregate and can also be used for aggregating multiple columns.
这将为您提供聚合的任何值的总计,也可用于聚合多个列。
Hope it helps!
希望能帮助到你!
回答by hellur
Well this should help you:
那么这应该可以帮助你:
select sum(innerselect.innertotal) as outertotal from
(select sum(size) as innertotal from mytable group by name) as innerselect