用户last_value填写日期

时间:2015-04-23 17:34:05

标签: oracle

我有下表。

MY_DAY      | STMT_DATE
------------+-------------
12/31/2013  | 12/31/2013
1/1/2014    | 
1/2/2014    | 1/2/2014
1/3/2014    | 1/3/2014
1/4/2014    | 
1/5/2014    | 
1/6/2014    | 1/6/2014
1/7/2014    | 1/7/2014
1/8/2014    | 1/8/2014
1/9/2014    | 1/9/2014
1/10/2014   | 1/10/2014
1/11/2014   | 
1/12/2014   | 
1/13/2014   | 1/13/2014
1/14/2014   | 1/14/2014

我希望为每一行获取STMT_DATE的前一个和后一个非空值。我正在使用以下查询:

      SELECT my_day,
         stmt_date,
         first_VALUE (stmt_date IGNORE NULLS) OVER (ORDER BY stmt_date asc ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) previous,
         first_VALUE (stmt_date IGNORE NULLS) OVER (ORDER BY stmt_date desc ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING)  next
    FROM DATE_TEST
ORDER BY my_day

但是我得到了以下结果:

MY_DAY     | STMT_DATE  | PREVIOUS   | NEXT
-----------+------------+------------+--------------
12/31/2013 | 12/31/2013 |            | 
1/1/2014   |            | 12/31/2013 | 1/14/2014
1/2/2014   | 1/2/2014   | 12/31/2013 | 12/31/2013
1/3/2014   | 1/3/2014   | 12/31/2013 | 1/2/2014
1/4/2014   |            | 12/31/2013 | 1/14/2014
1/5/2014   |            | 12/31/2013 | 1/14/2014
1/6/2014   | 1/6/2014   | 12/31/2013 | 1/3/2014
1/7/2014   | 1/7/2014   | 12/31/2013 | 1/6/2014
1/8/2014   | 1/8/2014   | 12/31/2013 | 1/7/2014
1/9/2014   | 1/9/2014   | 12/31/2013 | 1/8/2014
1/10/2014  | 1/10/2014  | 12/31/2013 | 1/9/2014
1/11/2014  |            | 12/31/2013 | 1/14/2014
1/12/2014  |            | 12/31/2013 | 1/14/2014
1/13/2014  | 1/13/2014  | 12/31/2013 | 1/10/2014
1/14/2014  | 1/14/2014  | 12/31/2013 | 1/13/2014

任何建议

2 个答案:

答案 0 :(得分:1)

经过一番工作,我得到了你问题的答案。

SELECT 
   my_day,
   stmt_date,
   LAST_VALUE (stmt_date IGNORE NULLS) OVER (ORDER BY my_day, stmt_date desc ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) Previous,
   FIRST_VALUE (stmt_date IGNORE NULLS) OVER (ORDER BY my_day, stmt_date desc ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING) Next
FROM 
   DATE_TEST
ORDER BY 
   my_day;

这里有一个有效的例子 http://sqlfiddle.com/#!4/f2fec/38

希望这有帮助

答案 1 :(得分:1)

通过使用函数lag()lead(),我们的语法更短:

select my_day, stmt_date,
    lag(stmt_date ignore nulls) over (order by my_day) previous,
    lead(stmt_date ignore nulls) over (order by my_day) next
  from date_test 
  order by my_day

SQLFiddle