Oracle 中的表行按月份汇总

Posted

技术标签:

【中文标题】Oracle 中的表行按月份汇总【英文标题】:Table rows summarize by Month in Oracle 【发布时间】:2021-03-08 08:17:21 【问题描述】:

我有以下 Oracle 表;

Site(VARCHAR2) Product Order Date(Date) Quantity(Number)
A X 3/5/2021 12:20:15 PM 100
B Y 3/5/2021 12:20:15 PM 200
A X 3/6/2021 12:20:15 PM 500
A Z 3/6/2021 12:20:15 PM 400

我需要从上表中生成类似于以下内容的摘要;

此处为特定产品生成摘要,以表明过去六个月的销售分布;

如何使用 Oracle SQL 实现这一点?

谢谢!

干杯, 女娲

【问题讨论】:

【参考方案1】:

使用 SQL,您在编写查询时必须知道您选择的列。但是您不知道,查询运行时的最后六个月是什么时候。这意味着:您不能选择名为 7 月到 12 月的列,因为查询可能会在 5 月运行。但是,您可以选择称为“当前月份”、“上个月”等的列。

select
  sum(case when order_date >= trunc(sysdate, 'mm')
           and order_date < order_date >= trunc(sysdate, 'mm') + interval '1' month
           then quantity
      end) as "current month",
  sum(case when order_date >= trunc(sysdate, 'mm') - interval '1' month
           and order_date < order_date >= trunc(sysdate, 'mm')
           then quantity
      end) as "last month",
  sum(case when order_date >= trunc(sysdate, 'mm') - interval '2' month
           and order_date < order_date >= trunc(sysdate, 'mm') - interval '1' month
           then quantity
      end) as "current month minus 2",
  sum(case when order_date >= trunc(sysdate, 'mm') - interval '3' month
           and order_date < order_date >= trunc(sysdate, 'mm') - interval '2' month
           then quantity
      end) as "current month minus 3",
  sum(case when order_date >= trunc(sysdate, 'mm') - interval '4' month
           and order_date < order_date >= trunc(sysdate, 'mm') - interval '3' month
           then quantity
      end) as "current month minus 4",
  sum(case when order_date >= trunc(sysdate, 'mm') - interval '5' month
           and order_date < order_date >= trunc(sysdate, 'mm') - interval '4' month
           then quantity
      end) as "current month minus 5",
  sum(case when order_date >= trunc(sysdate, 'mm') - interval '5' month
           and order_date < order_date >= trunc(sysdate, 'mm') + interval '1' month
           then quantity
      end) as total
from mytable
group by site
order by site;

如果您想将此限制为一种产品,请添加 WHERE 子句。

【讨论】:

以上是关于Oracle 中的表行按月份汇总的主要内容,如果未能解决你的问题,请参考以下文章

如何按 MS Access 的特定月份汇总特定列数据并进入 vb.net 中的文本框

前端每日实战 2018 年 9 月份项目汇总(共 26 个项目)

SQL Oracle 查询数据,汇总数据 oracle数据查询

ORACLE中用PLSQL如何把一个表中数据通过.DMP文件导出,再导入到另一个数据库的一个相同表结构的表中?

6月份文章分类汇总

福州大学2016软件工程89月份作业成绩汇总