如何在不同的列中显示每个值的倒数第二个日期

时间:2019-01-31 23:23:05

标签: sql oracle

我正在使用Oracle 12c,并且我有一个表,该表的各个列包括用于记录记录的日期列。我想确保我得到表中每个项目和位置组合的倒数第二个日期。

这是我为实现此目的而执行的SQL代码:

SELECT 
   DISTINCT 
   ITEM,
   LOCATION, 
   ORDER_POINT, 
   SAFETY_STOCK, 
   NTH_VALUE(REPL_DATE, 2) 
   OVER (PARTITION BY ITEM,LOCATION ORDER BY REPL_DATE DESC
   RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS PREVIOUS_DATE  
FROM 
   REPL_RESULTS

当我运行以下命令时,这里是结果示例:

SELECT 
   ITEM,
   LOCATION, 
   ORDER_POINT, 
   SAFETY_STOCK,
   REPL_DATE
FROM 
   REPL_RESULTS
ORDER BY ITEM, LOCATION

结果:

ITEM    LOCATION ORDER_POINT SAFETY_STOCK REPL_DATE 
0006296   100495    4.8416      0.1937     1/10/2019
0006296   100495    4.9021      0.2201     1/3/2019
0006296   100495    4.7848      0.15       11/22/2018
0006296   132142    3.1516      0.2481     1/9/2019
0006296   132142    2.091       0.23       1/16/2019
0006296   132142    2.903       0.1811     11/14/2018

我期望的结果是这样:

ITEM    LOCATION ORDER_POINT SAFETY_STOCK PREVIOUS_DATE 
0006296   100495    4.9021      0.2201     1/3/2019
0006296   132142    3.1516      0.2481     1/9/2019

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用Oracle窗口函数ROW_NUM()将行号分配给每个项目/位置组中按复制日期排序的每一行,然后过滤具有行号2的记录。

SELECT x.*
FROM (
    SELECT
        t.*,
        ROW_NUMBER() OVER(PARTITION BY t.item, t.location ORDER BY t.repl_date desc) rn
    FROM mytable t
) x WHERE x.rn = 2

demo on db fiddle 产生:

ITEM | LOCATION | ORDER_POINT | SAFETY_STOCK | REPL_DATE | RN
---: | -------: | ----------: | -----------: | :-------- | -:
6296 |   100495 |      4.9021 |        .2201 | 03-JAN-19 |  2
6296 |   132142 |      3.1516 |        .2481 | 09-JAN-19 |  2