Oracle每月总计和总计列和行

时间:2016-10-10 09:45:00

标签: sql oracle pivot

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

image

我收到了以下表格:

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(在地区下方)计算每个月的总数。
有任何想法如何添加此行?

2 个答案:

答案 0 :(得分:2)

您可以使用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); 

答案 1 :(得分:0)

尝试这样的事情:

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;