create table employee (id int, name varchar(20), salary int, department…
- User
create table employee (id int, name varchar(20), salary int, department varchar(20))insert into employee values (1, ‘John’, 100, ‘IT’), (2, ‘Sarah’, 110, ‘IT’), (3, ‘Rich’, 90, ‘IT’),(4, ‘Steve’, 80, ‘IT’), (5, ‘Anna’, 200, ‘HR’), (6, ‘Brandy’, 180, ‘HR’),(7, ‘Nancy’, 210, ‘HR’),(8, ‘Bob’, 190, ‘HR’),(9, ‘Cody’, 220, ‘HR’) , do the same result with window row_number function. self join with row_number = row_number + 1 based on those tables
- Assistant
To achieve the same result using the window row_number function and self join, you can follow the steps below:
Step 1: Create the employee table using the CREATE TABLE statement:
CREATE TABLE employee ( id INT, name VARCHAR(20), salary INT, department VARCHAR(20) );Step 2: Insert the values into the employee table using the INSERT INTO statement:
INSERT INTO employee VALUES (1, 'John', 100, 'IT'), (2, 'Sarah', 110, 'IT'), (3, 'Rich', 90, 'IT'), (4, 'Steve', 80, 'IT'), (5, 'Anna', 200, 'HR'), (6, 'Brandy', 180, 'HR'), (7, 'Nancy', 210, 'HR'), (8, 'Bob', 190, 'HR'), (9, 'Cody', 220, 'HR');Step 3: Use the ROW_NUMBER() function with the self join to get the desired result:
SELECT e1.id, e1.name, e1.salary, e1.department FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS row_num FROM employee ) e1 JOIN ( SELECT *, ROW_NUMBER() OVER (ORDER BY id) + 1 AS row_num FROM employee ) e2 ON e1.row_num = e2.row_num ORDER BY e1.id;This query will return the records from the employee table where the row number of the first occurrence is equal to the row number of the second occurrence + 1.