Postgres - 选择记录列表和一行总计

时间:2017-09-14 18:01:46

标签: sql postgresql

我有以下查询:

with charges as (
    select some_fields, (sum(subtotal_cents) as total from my_table 
    where <condition>
    group by some_field
) 
select <some_fields>, charges.total
from my_table
<lots_of_joins!>
left join charges on <condition>
where <condition>

假设总和是100,这给了我以下输出:

field_a | field_b | total
-----------------------
val1    | val2    | 100
val3    | val4    | 100

是否有可能取而代之(或接近它):

field_a | field_b | total
-----------------------
val1    | val2    | 
val3    | val4    | 
total   |         | 100

2 个答案:

答案 0 :(得分:0)

是的,通过使用UNION和一些棘手的命令:

with charges as (
    select some_fields, (sum(subtotal_cents) as total from my_table 
    where <condition>
    group by some_field
) 
SELECT *
FROM
    (
        select <some_fields>, CAST(NULL AS INTEGER) AS TOTAL, 0 AS sortorder
        from my_table
        <lots_of_joins!>
        UNION ALL
        SELECT 'total' as field_a, NULL as some_fields_2, NULL as some_fields_3, ..., charges.total, 1 as sortorder
    )
ORDER BY sortorder;

这里重要的事情是:

  1. 我们正在使用UNION来堆叠两个查询的结果(您的查询结果和您的CTE结果)
  2. 字段必须在序数和类型的两个Union'd查询之间排成一行,否则您将出错。
  3. 我们为排序顺序添加一个新列,将整个野兽推入子查询,然后按sortorder字段进行排序,以便您的CTE结果位于UNION'd结果的底部。

答案 1 :(得分:0)

是的,使用GROUPING SETSofficial documentation并没有太多示例,但我们假设您有一个包含三列的表:ab和{{1 }}

一个简单的小组会告诉你:

total

该SQL等同于# SELECT a, b, SUM(total) FROM foo GROUP BY a, b; a | b | sum ------+------+----- val1 | val2 | 100 val3 | val4 | 100 。您可以添加到该分组集列表中以获得总计:

SELECT a, b, SUM(total) FROM foo GROUP BY GROUPING SETS ((a, b))

显然,您必须针对更复杂的用例进行调整,但这应该相当简单。

修改:我使用简单的示例案例创建了sqlfiddle