2013-10-15 61 views
0

我有兩個表,示例如下。SQL Oracle - 在查詢中使用RowNum

table_1 
days  special_day 
10/09/2013  Y 
10/10/2013  N 
10/11/2013  Y 
10/12/2013  N 
10/13/2013  N 
10/14/2013  Y 

table_2 
id   special_day_ind  numdays   order 
123   Y     3    2 
456   N     5    1 

我的查詢將不得不選擇sysday和TABLE_1基於在TABLE_2參數正確的日期之間的差異。如果special_day_ind是'Y',那麼我需要從sysdate返回3(numdays)special_days。如果'N',那麼numdays就是答案。結果將是ORDER(ed)BY訂單asc(結束)。

在上面的表格示例中,查詢將返回。

SYSDATE = 2013年10月14日

id  days 
456  5 
123  5 (10/14/2013 - 10/9/2013) 

好像ROWNUM會做的伎倆,但具有計數的不同「方式」,我不知道如何着手。

+0

我想你需要看看[分析函數](http://www.oracle-base.com/articles/misc/lag-lead-analytic-functions.php)。 –

回答

0

這是一種方法。

您需要爲table_1中的特殊日子分配一個行號。

select days, 
     row_number() over (order by days desc) r 
    from table_1 
where special_day = 'Y'; 

使用此作爲CTE,你可以找到早期的特殊日子,並從sysdate中減去它。

with x as(
    select days, 
     row_number() over (order by days desc) r 
    from table_1 
    where special_day = 'Y' 
) 
select id, 
     case when special_day_ind = 'N' 
      then numdays 
      when special_day_ind = 'Y' 
      then trunc(sysdate) - (select days 
            from x 
            where r = numdays) 
     end days 
    from table_2 
order by order_; 

Demo