2015-11-04 50 views
0

你好,我有一個lead的問題,並從下一組中檢索下一個值。Oracle由組導致

我有這個表:

表A

----------------- 
    ID | value 
----------------- 
    1  | 2.5  
    1  | 1  
    1  | 4.5  
    2  | 7  
    2  | 2 
    3  | 3 
    4  | 1 
    4  | 7 

預期結果:

------------------------------ 
    ID | value | lead_id 
------------------------------ 
    1  | 2.5 | 2 
    1  | 1  | 2 
    1  | 4.5 | 2 
    2  | 7  | 3 
    2  | 2  | 3 
    3  | 3  | 4 
    4  | 1  | NULL 
    4  | 7  | NULL 

我的SQL:

select ID, value, lead(id) OVER (order by id) lead_id from TableA 

是否有可能得到這一結果?

+0

我們看到您的預期結果。但是,我們沒有看到您的實際結果。你得到的錯誤結果是什麼? – nop77svk

+0

我認爲你得到lead_ID-1是你期望在前兩行得到lead_ID-2,這是因爲lead不會給你下一個不同的值,而是下一個實際的值。這意味着在你的情況下,前兩行的lead_id是1,只有第三行的lead值是2。 –

回答

1

您可以通過添加在窗口條款列入FIRST_VALUE解析函數做到這一點:

with tablea as (select 1 id, 2.5 value from dual union all 
       select 1 id, 1 value from dual union all 
       select 1 id, 4.5 value from dual union all 
       select 2 id, 7 value from dual union all 
       select 2 id, 2 value from dual union all 
       select 3 id, 3 value from dual union all 
       select 4 id, 1 value from dual union all 
       select 4 id, 7 value from dual) 
select id, 
     value, 
     first_value(id) over (order by id 
          range between 1 following and unbounded following) lead_id 
from tablea; 

     ID  VALUE LEAD_ID 
---------- ---------- ---------- 
     1  2.5   2 
     1   1   2 
     1  4.5   2 
     2   7   3 
     2   2   3 
     3   3   4 
     4   1   
0

我覺得這給正確的輸出:

WITH g AS 
    (SELECT ID, lead(ID) OVER (ORDER BY ID) lead_id 
    FROM (SELECT DISTINCT ID FROM TableA)) 
SELECT ID, VALUE, lead_id 
FROM TableA 
    JOIN g USING (ID) 
ORDER BY 1; 
0
SELECT tablea.*, b.nextid FROM tablea 
    INNER JOIN (SELECT id, LEAD (id) OVER (ORDER BY id) nextid 
       FROM ( SELECT DISTINCT id 
          FROM tablea 
          ORDER BY id)) b 
     ON tablea.id = b.id 

這應該工作。