SQL select 当前交易和参考最近交易

SQL select current transaction and reference most recent transaction

可以在 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 |
+-------+----------+------------+------------+-------+------------------+---------------+------------+

提前致谢!

使用解析函数生成 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 

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

您应该可以使用 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.

另一个使用 Oracle 分析函数的解决方案(虽然使用了 Windowing 子句)。您可以找到@Sathya 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