SQL比较列并计算差异

时间:2013-11-13 11:02:35

标签: sql database oracle11g

我正在使用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

我想要做的是每个产品的总量,然后比较两个月的量,并有一个计算字段计算差异,所以我最终得到:

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;

1 个答案:

答案 0 :(得分: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')
       )