Oth*_*hya 3 sql postgresql group-by
如何在此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 --
Run Code Online (Sandbox Code Playgroud)
运行上面的代码会产生:
|*Section* | *Money* | *Requests*|
|-----------|---------|-----------|
|BMO - HR |564 |10 |
|BMO - ITB |14707 |407 |
|BMO - test |15 |7 |
Run Code Online (Sandbox Code Playgroud)
现在,我想要在显示的末尾添加总计:
|BMO - Total|15286 |424 |
Run Code Online (Sandbox Code Playgroud)
我尝试了几件事,最后以尝试将选择包装在WITH语句中而失败:
WITH w as (
--SELECT statement from above--
)
SELECT * FROM w UNION ALL
SELECT 'Total', money, requests from w
Run Code Online (Sandbox Code Playgroud)
这会产生奇怪的结果(我总共得到四行-当应该只有一行时。
任何帮助将非常感激!
谢谢
此/sf/answers/3843921651/答案中的汇总功能可能是一种方便的方法。更多关于这个和相关功能的信息: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))
Run Code Online (Sandbox Code Playgroud)
注意双括号,它们很重要
您可以通过使用UNION查询来实现。在下面的查询中,我添加了一个人工排序列,并将联合查询包装在外部查询中,以便总和行显示在底部。
[我假设您将添加联接和group by子句...]
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5942 次 |
| 最近记录: |