【问题标题】:Oracle monthly totals and grand total column and rowOracle 每月总计和总计列和行
【发布时间】:2016-10-10 09:44:59
【问题描述】:

我正在尝试使用 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(区域下方)之外,问题已解决。
有什么想法可以添加这一行吗?

【问题讨论】:

  • 不需要SELECT DISTINCT,因为GROUP BY 不会返回重复项。
  • COALESCE(NULL, NULL)是什么意思?
  • 我只使用 COALESCE 来生成表头...
  • 你有一些测试数据吗?另外,您的 Oracle 版本是什么?几点观察:在 Oracle 11 或更高版本中,您可以使用 PIVOT 操作。如果性能很重要,则不应从 Sale_Date 中提取月份 - 您应该在该列上有一个索引,并以允许使用该索引的方式编写过滤器。 (在其上使用“提取”或任何其他函数将阻止使用索引。)此外,最好避免在双引号中使用列名,特别是如果此查询的输出是或可能是(将来)用于进一步处理。

标签: sql oracle pivot


【解决方案1】:

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

【讨论】:

  • 运行良好!但是如何添加第二个总计(在区域下方)并计算总计?
  • @Mr.Gigi - 我编辑了解决方案来回答您剩下的问题。请阅读“按汇总分组”(Google 是您的朋友)。
【解决方案2】:

试试这样的:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    相关资源
    最近更新 更多