COMPLEX SQL: write a SQL query to interchange the adjacent student names.(LEAD and LAG functions perfect example)

From the students table, write a SQL query to interchange the adjacent student names.

Note: If there are no adjacent student then the student name should stay the same.

Table Name: STUDENTS

Approach: Assuming id will be a sequential number always. If id is an odd number then fetch the student name from the following record. If id is an even number then fetch the student name from the preceding record. Try to figure out the window function which can be used to fetch the preceding the following record data.

If the last record is an odd number then it wont have any adjacent even number hence figure out a way to not interchange the last record data.

Create table

create table students
(
id int primary key,
student_name varchar(50) not null
);

Data population:
insert into students values(1, ‘James’);
insert into students values(2, ‘Michael’);
insert into students values(3, ‘George’);
insert into students values(4, ‘Stewart’);
insert into students values(5, ‘Robin’);

Solution:

SELECT ID,STUDENT_NAME,
CASE WHEN MOD(ID,2) <> 0 THEN LEAD(STUDENT_NAME,1,STUDENT_NAME) OVER (ORDER BY ID)
WHEN MOD(ID,2) = 0 THEN LAG(STUDENT_NAME) OVER (ORDER BY ID)
END AS ADJACENT_NAME
FROM STUDENTS;

Output:

1     James       Michael
2    Michael    James
3     George    Stewart
4     Stewart   George
5     Robin      Robin

Popular posts from this blog

Window function in PySpark with Joins example using 2 Dataframes (inner join)

Complex SQL: fetch the users who logged in consecutively 3 or more times (lead perfect example)

Credit Card Data Analysis using PySpark (how to use auto broadcast join after disabling it)