【问题标题】:How to add a 'total' row in a grouped query (in Postgresql)?如何在分组查询中添加“总计”行(在 Postgresql 中)?
【发布时间】:2015-03-05 17:57:32
【问题描述】:

如何在此 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        |

我尝试了一些方法,最终尝试将选择包装在 WITH 语句中但失败了:

WITH w as (
    --SELECT statement from above--
)
SELECT * FROM w UNION ALL 
   SELECT 'Total', money, requests from w

这会产生奇怪的结果(我总共得到了四行 - 当应该只有一个时。

任何帮助将不胜感激!

谢谢

【问题讨论】:

  • 你必须 SUM() 结果:SELECT 'Total', SUM(money), SUM(requests) from w

标签: sql postgresql group-by


【解决方案1】:

您可以通过使用 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

【讨论】:

    【解决方案2】:

    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))
    

    注意双括号,它们很重要

    【讨论】:

    • 这是一个工作示例WITH w AS ( SELECT * FROM ( VALUES ('BMO - HR', 564, 10), ('BMO - ITB', 14707, 407), ('BMO - test', 15, 7) ) t (Section, Money, Requests) ) SELECT Section, sum(Money), sum(Requests) FROM w GROUP BY ROLLUP ((Section, Money, Requests))
    猜你喜欢
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 2012-07-26
    相关资源
    最近更新 更多