我有分支机构的销售数据。我想要一个SQL,它可以为我提供每个branchId的销售数据摘要,如下所示,当然BranchId很大,因此我必须使其动态化(我不能使用Union)。我被困在如何动态地更改每个分支之后添加摘要行。
+ ---------+--------+---------+-----------+ | BranchId | CashIn | CashOut | CardSales | + ---------+--------+---------+-----------+ | 1 | 1000 | 500 | 50 | | 1 | 500 | 2500 | 100 | | 1 | 1000 | 200 | 200 | | Totals | 2500 | 3200 | 350 | | 5 | 100 | 500 | 500 | | Totals | 100 | 500 | 500 | | 7 | 100 | 100 | 100 | | 7 | 200 | 300 | 400 | | Totals | 300 | 400 | 500 | + ---------+--------+---------+-----------+
答案 0 :(得分:1)
蛮力方法是进行汇总,然后对结果进行交织:
select (case when is_base = 1 then to_char(BranchId)
else replace('Total ([BranchId])', '[BranchId]', BranchId)
end) as BranchId, CashIn, CashOut, CardSales
from ((select BranchId, CashIn, CashOut, CardSales, 1 as is_base
from t
) union all
(select BranchId, sum(CashIn), sum(CashOut), sum(CardSales), 0 as is_base
from t
group by BranchId
)
) t
order by t.BranchId, is_base desc;
Here是db <>小提琴。