简体   繁体   中英

THREE ROWS LEAD FUNCTION IN ORACLE PL SQL

My Table:

ID  NAME
1   SIVA
2   RAJA
3   PYTHON
4   SQL
5   ODI

I need to lead by 3 rows.

My SQL Query:

SELECT LEAD(NAME,3) OVER (ORDER by NAME) as NAME FROM TEST_TABLE where NAME='SIVA' 

EXPECTED OUTPUT:

--------
| NAME |
--------
| SQL  |
--------

Example:

If I pass value as SIVA, then I need to get SQL as output.

Similarly if I pass value as Raja, then I need to get ODI as output

Is there any query to get the expected output?

This might be one option: it uses row_number analytic function which calculates row numbers so that you wouldn't have to rely on ID values. What if they are acquired by a sequence? It is not gapless. Basically - it is used for safety .

SQL> WITH test (id, name)
  2       AS (SELECT 1, 'siva' FROM DUAL
  3           UNION ALL
  4           SELECT 2, 'raja' FROM DUAL
  5           UNION ALL
  6           SELECT 3, 'python' FROM DUAL
  7           UNION ALL
  8           SELECT 4, 'sql' FROM DUAL
  9           UNION ALL
 10           SELECT 5, 'odi' FROM DUAL),
 11       temp AS (SELECT id, name, ROW_NUMBER () OVER (ORDER BY id) rn FROM test)
 12  SELECT b.name
 13    FROM temp a JOIN temp b ON b.rn = a.rn + 3
 14   WHERE a.name = '&name';
Enter value for name: siva

NAME
------
sql

SQL> /
Enter value for name: raja

NAME
------
odi

SQL> /
Enter value for name: sql

no rows selected

SQL>

You can simply use sub-query :

SELECT Next_NAME 
FROM (SELECT NAME, LEAD(NAME, 3) OVER (ORDER by id) AS Next_NAME 
      FROM TEST_TABLE
     ) t
WHERE NAME = 'SIVA';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM