user2989578
user2989578

Reputation: 1

Fetching row of a table and moving across column of another table

Given a table like this with single column,

Names 
------
A
B
C
D
E

Take each record from table and check previous and next value and put it across new table. Print 'null' if no previous or next value exists with column name as prev_name,current_name,next

Prev_name| Current name| next
-----------------------------
NULL     | A           |B
A        | B           |C 
B        | C           |D 
C        | D           |E 
D        | E           |NULL

I am learning SQL and googled to find something which might help solve this but couldn't.

Any help will be great!

Upvotes: 0

Views: 39

Answers (1)

Santhosh
Santhosh

Reputation: 1791

See this link in fiddle, Query. But NULLS are considered as spaces and omitted in string concatenation.

Please use this query

  SELECT LAG(NAMES) OVER(ORDER BY NAMES) AS PREV_NM,  NAMES,
  LEAD(NAMES) OVER(ORDER BY NAMES) AS NEXT_NM
  FROM SAMPLE

Fiddle link is changed.

Upvotes: 2

Related Questions