2013-04-29 66 views
6

Last_value窗口功能doesn't正常工作。Last_value窗口功能不能正常工作

CREATE TABLE EXAMP2 
(
    CUSTOMER_ID NUMBER(38)      NOT NULL, 
    VALID_FROM DATE        NOT NULL 
); 


Customer_id  Valid_from 
------------------------------------- 
9775    06.04.2013 01:34:16 
9775    06.04.2013 20:34:00 
9775    12.04.2013 11:07:01 
-------------------------------------- 

select DISTINCT LAST_VALUE(VALID_FROM) 
    OVER (partition by customer_id ORDER BY VALID_FROM ASC) rn 
from examp1; 

當我使用LAST_VALUE然後我得到以下行:

06.04.2013 20:34:00 
06.04.2013 01:34:16 
12.04.2013 11:07:01 

當我使用FIRST_VALUE然後我獲得以下行:

select DISTINCT FIRST_VALUE(VALID_FROM) 
OVER (partition by customer_id ORDER BY VALID_FROM DESC) rn 
from examp1; 

4/12/2013 11:07:01 AM 

First_value查詢給出正確的輸出。我希望從這些查詢中獲得相同的輸出。爲什麼我有​​?

+0

這適用於**的Microsoft SQL Server **以及 – Jaider 2017-02-01 21:02:08

回答

5

first_valuelast_value有點特別,它們需要一個窗口來操作。

您需要添加ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING如下:

select DISTINCT LAST_VALUE(VALID_FROM) OVER (partition by customer_id 
    ORDER BY VALID_FROM ASC 
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) rn 
from examp1; 

參見文檔:http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions001.htm#i81407和閱讀特別是在開窗部分。並不是說接受窗口條款的函數的默認子句是RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW,這就解釋了爲什麼一個訂單可以工作,而另一個訂單卻不行!

9

在分析函數中,您需要指定窗口範圍。默認情況下它是between unbounded preceding and current row,我認爲這是不言自明的。

基本上,這是當你指定partition by customer_id order by valid_from asc會發生什麼:

  1. 甲骨文需要搭配全行當前行的customer id
  2. 它通過valid_from
  3. 它形成了一個窗口開始預定他們以升序最少valid_from日期,結束於當前行的valid_from
  4. 它評估last_value,它返回您當前行的valid_from

你需要做的就是指定一個持續的範圍是什麼:

16:53:00 [email protected]> ed 
Wrote file S:\spool\sandbox\BUFFER_SYSTEM_38.sql 

    1 select last_value(VALID_FROM) OVER (
    2 partition by customer_id 
    3 ORDER BY VALID_FROM asc 
    4 range between current row and unbounded following 
    5 ) rn 
    6* from t 
16:53:21 [email protected]>/

RN 
--------------------------------------------------------------------------- 
04-DEC-13 11.07.01.000000 AM 
04-DEC-13 11.07.01.000000 AM 
04-DEC-13 11.07.01.000000 AM 

Elapsed: 00:00:00.01