SQL选择当前事务并引用最近的事务

时间:2015-01-13 05:41:10

标签: sql oracle oracle11g analytics

可以在Oracle 11G中使用一些SQL帮助。我正在尝试创建一个结果集,该结果集接受当前事务,查找最近的相关事务,显示当前价格以及之前的价格,然后计算差异。

假设每个项目在给定月份只能有一个价格。如果没有可用的早期数据,则显示当前值。

原始数据看起来像:

+-------+----------+------------+------------+-------+
| Item  | Location | Department |  MonthEnd  | Price |
+-------+----------+------------+------------+-------+
| Truck | Illinois | BusinessA  | 4/30/2014  | 10000 |
| Truck | Illinois | BusinessA  | 6/30/2014  |  9500 |
| Truck | Illinois | BusinessA  | 10/31/2014 |  8000 |
+-------+----------+------------+------------+-------+

查询结果如下所示:

+-------+----------+------------+------------+-------+------------------+---------------+------------+
| Item  | Location | Department |  MonthEnd  | Price | PreviousMonthEnd | PreviousPrice | PriceDelta |
+-------+----------+------------+------------+-------+------------------+---------------+------------+
| Truck | Illinois | BusinessA  | 10/31/2014 |  8000 | 6/30/2014        |          9500 |      -1500 |
| Truck | Illinois | BusinessA  | 6/30/2014  |  9500 | 4/30/2014        |         10000 |       -500 |
| Truck | Illinois | BusinessA  | 4/30/2014  | 10000 | 4/30/2014        |         10000 |          0 |
+-------+----------+------------+------------+-------+------------------+---------------+------------+

提前致谢!

3 个答案:

答案 0 :(得分:2)

你应该可以使用Lag analytical function来获得它。查询将如下所示。

SELECT Item,
       Location,
       Department,
       MonthEnd,
       Price,
       COALESCE(LAG (MonthEnd, 1) OVER (ORDER BY MonthEnd),  MonthEnd) PrevMonthEnd,
       COALESCE(LAG (Price, 1)    OVER (ORDER BY MonthEnd),  price)    PrevPrice ,
       (price - coalesce(LAG (Price, 1) OVER (ORDER BY MonthEnd), price)) PriceDelta
FROM   items
ORDER BY monthend desc

这里是SQLFiddle testing this.

答案 1 :(得分:1)

使用分析函数生成row_numberLeft join结果。试试这个。

WITH cte
     AS (SELECT *,Row_number()OVER (ORDER BY MonthEnd DESC) rn

         FROM   yourtable)
SELECT a.Item,
       a.Location,
       a.Department,
       a.MonthEnd,
       a.Price,
       COALESCE(( a.Price - b.Price ), a.price)
FROM   cte a
       LEFT JOIN cte b
              ON a.rn = b.rn - 1 

注意:根据您的要求,您可以在Partition by子句

中添加Over

答案 2 :(得分:1)

另一种使用Oracle的分析功能的解决方案(尽管使用了Windowing子句)。你可以找到@ Sathya' s SQLFiddle here

的修改版本

查询如下:

SELECT Item,
       Location,
       Department,
       MonthEnd,
       Price,
       MIN(monthend) OVER (PARTITION BY item,location,department ORDER BY item,location,department,monthend ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) PrevMonthEnd,
       NVL(SUM(price) OVER (PARTITION BY item,location,department ORDER BY item,location,department,monthend ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING),price) PrevPrice ,
       (price - NVL(SUM(price) OVER (PARTITION BY item,location,department ORDER BY item,location,department,monthend ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING),price)) PriceDelta
FROM   items
ORDER BY monthend DESC