Oracle 每月总计和总计列和行

Oracle monthly totals and grand total column and row

我正在尝试使用 Oracle 生成如下所示的报告:

我得到了下表:

REGION (IDRegion, Region_Name) 
SALES (IDSale, Sale_Date, Amount, IDSaleRegion)
Both tables are populated.  

我不知道如何通过提取前 3 个月的每笔金额并计算总计来创建该报告。
我只做了这个脚本,但用处不大:

SELECT Region_Name as Region, 
COALESCE(NULL, NULL) AS "January", 
COALESCE(NULL, NULL)AS"February", 
COALESCE(NULL, NULL)AS"March", 
COALESCE(NULL, NULL)AS"GrandTotal"
FROM REGION r INNER JOIN SALES s ON r.IDRegion=s.IDSaleRegion
GROUP BY Region_Name;


编辑:除了 TOTAL(区域下方)计算每个月的总计之外,问题已解决。
知道如何添加此行吗?

您可以使用Conditional Aggregation

select case grouping(Region_Name) when 1 then 'TOTAL' else Region_Name as "Region",
       sum(case when extract(month from Sale_Date) = 1 then Amount else 0 end) AS "January",
       sum(case when extract(month from Sale_Date) = 2 then Amount else 0 end) AS "February",
       sum(case when extract(month from Sale_Date) = 3 then Amount else 0 end) AS "March",
       sum(Amount) AS"GrandTotal"
From yourtable
Where extract(month from Sale_Date) <= 3
Group by Rollup (Region_Name); 

尝试这样的事情:

SELECT Region_Name as Region, 
sum(decode(extract(month from Sale_Date), 1, amount)) AS "January", 
sum(decode(extract(month from Sale_Date), 2, amount)) AS"February", 
sum(decode(extract(month from Sale_Date), 3, amount)) AS"March", 
sum(case when extract(month from Sale_Date)<4 then amount end) AS"GrandTotal"
FROM REGION r INNER JOIN SALES s ON r.IDRegion=s.IDSaleRegion
GROUP BY Region_Name;