oracle查询根据当前日期检索最接近和第二近的未来日期

时间:2017-07-28 12:25:44

标签: oracle

我想根据当前日期检索最接近和第二近的未来日期。 例如: 当前最新= 28-07-2017

要检索的日期

28-07-2017 29-07-2017

或跟随最接近当前日期的前两个日期。

plzz帮助我在oracle中编写这个查询

2 个答案:

答案 0 :(得分:0)

试试这个:

select sysdate,sysdate + level "Dates" From   DUAL connect by level <= 1 ;

答案 1 :(得分:0)

您可以使用dense_rank分析函数执行此操作,如下所示:

WITH sample_data AS (SELECT 1 ID, to_date('01/07/2017', 'dd/mm/yyyy') dt FROM dual UNION ALL
                     SELECT 2 ID, to_date('02/07/2017', 'dd/mm/yyyy') dt FROM dual UNION ALL
                     SELECT 3 ID, to_date('02/07/2017', 'dd/mm/yyyy') dt FROM dual UNION ALL
                     SELECT 4 ID, to_date('03/07/2017', 'dd/mm/yyyy') dt FROM dual UNION ALL
                     SELECT 5 ID, to_date('04/07/2017', 'dd/mm/yyyy') dt FROM dual UNION ALL
                     SELECT 6 ID, to_date('05/07/2017', 'dd/mm/yyyy') dt FROM dual UNION ALL
                     SELECT 7 ID, to_date('06/07/2017', 'dd/mm/yyyy') dt FROM dual)
SELECT ID, dt
FROM   (SELECT ID,
               dt,
               dense_rank() OVER (ORDER BY dt) dr
        FROM   sample_data
        WHERE  dt >= to_date('01/07/2017', 'dd/mm/yyyy'))
WHERE  dr <= 2;

        ID DT
---------- -----------
         1 01/07/2017
         2 02/07/2017
         3 02/07/2017