I am having one table that contain 3 columns named as ID,logged_in,Logged_out.
ID | logged_in | logged_out |
---|---|---|
24456 | 10:00:00 | 11:20:00 |
24456 | 11:30:00 | 13:00:00 |
24456 | 13:30:00 | 16:10:00 |
24456 | 16:20:00 | 19:00:00 |
I want to subtract Second row from logged_in with First row from logged_out and store the data into a new column and if there is nothing to subtract it need to populates as 00:00:00.
Ex: 2nd row from Logged_in is 11:30:00 and 1st row from logged_out is 11:20:00 so the output will be 11:30:00 - 11:20:00 =0:10:00
expected Output will be like this.
ID | logged_in | logged_out | Total_duration |
---|---|---|---|
24456 | 10:00:00 | 11:20:00 | 00:10:00 |
24456 | 11:30:00 | 13:00:00 | 00:30:00 |
24456 | 13:30:00 | 16:10:00 | 00:10:00 |
24456 | 16:20:00 | 19:00:00 | 00:00:00 |
Using TIME_DIFF()
with LEAD()
we can try:
SELECT ID, logged_in, logged_out,
COALESCE(TIME_DIFF(LEAD(logged_in) OVER (ORDER BY logged_in),
logged_out,
MINUTE), 0) AS Total_duration
FROM yourTable
ORDER BY logged_in;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.