Oracle Lead by group

时间:2015-11-04 12:46:23

标签: oracle lead

您好我lead遇到了问题,并从下一组中检索了下一个值。

我有这张桌子:

TableA

-----------------
   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

是否可以获得该结果?

3 个答案:

答案 0 :(得分: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           

答案 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;

答案 2 :(得分: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

这应该有用。