-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlead_and_lag_function_in_sql.sql
More file actions
30 lines (22 loc) · 1.16 KB
/
lead_and_lag_function_in_sql.sql
File metadata and controls
30 lines (22 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
use sakila;
show tables;
select * from film;
-- lead function is used to access subsequent row data along with current row data
-- lag function is used to access previous row data along with current row data
-- order by req
-- partition by optional
-- lead(col_name, offset, default_value) over (order by col1, col2...)
-- here offset means how many rows before or after you want the data by default it is 1 so lets say data is like this 1, 3, 4, 6 then lead(1) will be 3, 4, 6, NULL and lead(2) will be 4, 6, NULL, NULL
-- default value means if the next row or previous row is not present then this will be given by default it is NULL
select title, release_year, rental_duration, length,
LEAD(length) over (order by length) as lead_value
from film limit 10;
select title, release_year, rental_duration, length,
LAG(length) over (order by length) as lead_value
from film limit 10;
select title, release_year, rental_duration, length,
LEAD(length) over (partition by rental_duration order by length) as lead_value
from film limit 10;
select title, release_year, rental_duration, length,
LAG(length) over (partition by rental_duration order by length) as lead_value
from film limit 10;