create table employee (id int, name varchar(20), salary int, department varchar(20))…
- 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-joins, you can execute the following SQL queries:
Step 1: Create the employee table
CREATE TABLE employee ( id INT, name VARCHAR(20), salary INT, department VARCHAR(20) );Step 2: Insert data into the employee table
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: Retrieve the result using self-joins and ROW_NUMBER() function
SELECT e1.id, e1.name, e1.salary, e1.department FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS rn FROM employee ) e1 JOIN ( SELECT *, ROW_NUMBER() OVER (ORDER BY id) AS rn FROM employee ) e2 ON e1.rn = e2.rn + 1;This query assigns row numbers to each row in the "employee" table based on the id column. It then performs a self-join on the table using the row number and row number + 1 condition to retrieve the desired result.