如何在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
这会产生奇怪的结果(我总共得到四行 - 当时应该只有一行。
非常感谢任何帮助!
由于
答案 0 :(得分:2)
您可以使用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
答案 1 :(得分:0)
此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))
请注意双括号,它们是有效的