我有以下查询:
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
答案 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;
这里重要的事情是:
sortorder
字段进行排序,以便您的CTE结果位于UNION'd结果的底部。答案 1 :(得分:0)
是的,使用GROUPING SETS
。 official documentation并没有太多示例,但我们假设您有一个包含三列的表:a
,b
和{{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。