2015-04-23 63 views
2

我有下表。用戶last_value填寫日期

 
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 

任何建議

回答

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

+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

希望這有助於