[英]How to add a 'total' row in a grouped query (in Postgresql)?
如何在SELECT的末尾添加一行,以便查看分组行的总数? (我需要'钱'和'请求'的总额:
SELECT
organizations.name || ' - ' || section.name as Section,
SUM(requests.money) as money,
COUNT(*) as requests
FROM
schema.organizations
-- INNER JOINs omitted --
WHERE
-- omitted --
GROUP BY
-- omitted --
ORDER BY
-- omitted --
运行以上产生:
|*Section* | *Money* | *Requests*|
|-----------|---------|-----------|
|BMO - HR |564 |10 |
|BMO - ITB |14707 |407 |
|BMO - test |15 |7 |
现在我想要的是在显示的结尾添加一个总数:
|BMO - Total|15286 |424 |
我尝试了一些事情,最后尝试将select包装在WITH语句中并失败:
WITH w as (
--SELECT statement from above--
)
SELECT * FROM w UNION ALL
SELECT 'Total', money, requests from w
这会产生奇怪的结果(我总共得到四行 - 应该只有一行。
任何帮助将非常感激!
谢谢
您可以使用UNION查询来实现此目的。 在下面的查询中,我添加了一个人工排序列并将联合查询包装在外部查询中,以便总和行显示在底部。
[我假设你将按条款添加你的联接和分组......]
SELECT section, money, requests FROM -- outer select, to get the sorting right.
( SELECT
organizations.name || ' - ' || section.name as Section,
SUM(requests.money) as money,
COUNT(*) as requests,
0 AS sortorder -- added a sortorder column
FROM
schema.organizations
INNER JOINs omitted --
WHERE
-- omitted --
GROUP BY
-- omitted --
-- ORDER BY is not used here
UNION
SELECT
'BMO - Total' as section,
SUM(requests.money) as money,
COUNT(*) as requests,
1 AS sortorder
FROM
schema.organizations
-- add inner joins and where clauses as before
) AS unionquery
ORDER BY sortorder -- could also add other columns to sort here
此https://stackoverflow.com/a/54913166/1666637答案中的汇总功能可能是一种方便的方法。 有关此功能和相关功能的更多信息,请访问: https : //www.postgresql.org/docs/devel/queries-table-expressions.html#QUERIES-GROUPING-SETS
这样的东西,未经测试的代码
WITH w as (
--SELECT statement from above--
)
SELECT * FROM w ROLLUP((money,requests))
注意双括号,它们很重要
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.