Complex SQL: 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.

–Table Structure:

drop table students;
create table students
(
id int primary key,
student_name varchar(50) not null
);
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’);

select * from students;

Solution:

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)