如何在分组查询中添加 'total' 行(在 Postgresql 中)?

How to add a 'total' row in a grouped query (in Postgresql)?

如何在此 SELECT 末尾添加一行,以便查看分组行的总数? (我需要 'money' 和 'requests' 的总数:

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

rollup函数在这个 answer might be a convenient way to do this. More on this and related functions here: 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))

注意双括号,它们很重要