1

我正在使用 Oracle 11gR2

例如,我有一张桌子:

ProductName   |   Volume   |   Date
-------------------------------------------
ProdA         |   1000     |   11-Oct-2013
ProdA         |   2000     |   16-Oct-2013
ProdB         |   500      |   12-Oct-2013

ProdA         |   200      |   11-Nov-2013
ProdB         |   100      |   16-Nov-2013
ProdB         |   300      |   12-Nov-2013

我想要做的是合计每个产品的数量,然后比较 2 个月的数量,并计算出一个计算字段来计算差异,所以我最终会得到:

ProductName   |   VolumeCurrentMonth   |   VolumePrevMonth   |   Difference
-------------------------------------------
ProdA         |   200                  |   3000              |    -2800
ProdB         |   400                  |   500               |    -100

我的代码远未满足要求,但无论如何我都会发布它:

Select ProductName, sum(Volume), to_char(Date, 'Month') as Current_Month, to_char(run_date, 'Month') as PY_Month
from Sales
where Date is not null
group by ProductName, Date;
4

1 回答 1

1

我将采取两步方法——首先,按产品和月份分组的内部查询。LAG然后,外部查询可以使用分析函数处理与上个月的比较:

SELECT productName, volume_sum AS curr_month_sum, 
       LAG(volume_sum) OVER (PARTITION BY productName ORDER BY month)
FROM   (SELECT    productName, trunc(theDate, 'MM-YYYY') AS month, SUM(volume) as volume_sum
        FROM      some_table
        GROUP BY  productName, trunc(theDate, 'MM-YYYY')
       )
于 2013-11-13T11:11:05.943 回答