Table 行在 Oracle 中按月份汇总

Table rows summarize by Month in Oracle

我有以下 Oracle table;

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

我需要根据上面的内容生成类似于以下内容的摘要 table;

此处,为特定产品生成摘要以指示过去六个月的销售差价;

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

谢谢!

干杯, 女弯

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

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 子句。