Hello Everyone,
Good evening, how are you all, a hope you all guys will happy and good. By the grace of God, I am also good. In SQL, there are many super and useful function that are used for data manipulation and data analysis, a function that I will be discussed here are called Lag function. We will explain what it does and how we can use it and why it is so handy for getting insights from our data.
The Lag function is used in SQL that allows us to access data from the previous row within the result set. It is particularly useful when we need to compare the current row with the preceding row or perform calculations based on historical data.
LAG(column_expression [, offset [, default_value]]) OVER (ORDER BY order_expression)
- column_expression refers to the set of data that we want to look at from the previous row in our table.
- offset tells SQL how many rows back you want to look from the current row.
- default_value is the value that a function will return if it cannot find a row at the specified offset. If we do not provide a default_value then it will return as NULL.
- It is about how rows are sorted within a specific partition/group in data set.
let's discussed by practically.
I have created a table tbd_lag containing employee data with columns EMPCODE, EMPNAME, JOININGDATE, PREV_CUSTOMER now we will retrieve each employees previous joining date (if it exists), grouped by EMPCODE and ordered by JOININGDATE within each group.
select * from (
select a.* ,
LAG(a.JOININGDATE) OVER (PARTITION BY a.EMPCODE ORDER BY a.JOININGDATE ) PREV_CUSTOMER
from tbd_lag a ) a
First of all, i am going to use the select statement to run and show the whole data inside table.
Now I am using lag function on the base of JOININGDATE. the above query group the data on the base of empcode and get the previous joining date of employees that have more than one entry.
It would be my pleasure if you will share your opinion and reviews on this topic
Please cast witness vote to @bangla.Witness or set proxy to @rme.
_
Vote @bangla.witness as witness
Set Proxy @rme as proxy
Special Thanks.
Cc: @rme
Cc: @hungry-griffin
Cc: @pennsif
Thanks for giving your precious time to my post.
Follow | Upvote | Share | Comments
Follow me on Instagram.
Instagram
🆃🅷🅰️🅽🅺 🆈🅾️🆄
Upvoted! Thank you for supporting witness @jswit.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit