1

I have a little trouble here. If i have the following table:

ID  | Name | ini_day
-----------------------
1   | Juan | 1
2   | Nora | 5
3   | Pepe | 9
4   | Lara | 12
5   | Alex | 18
6   | Lily | 20  

I need to calculate the last day of work based in the next ini_day minus 1. Expected result:

ID  | Name | ini_day | end_day
------------------------------
1   | Juan | 1       | 4
2   | Nora | 5       | 8
3   | Pepe | 9       | 11
4   | Lara | 12      | 17
5   | Alex | 18      | 19
6   | Lily | 20      | NULL

How i achieve it? Thanks in advance!

1
  • what is your mysql version? Check using SELECT VERSION(); Commented Apr 30, 2024 at 11:07

2 Answers 2

2

On MySQL 8+, we can use the LEAD() window function:

SELECT ID, Name, ini_day, LEAD(ini_day) OVER (ORDER BY ID) - 1 AS end_day
FROM yourTable
ORDER BY ID;
Sign up to request clarification or add additional context in comments.

Comments

0

According to documentation of MYSQL

LEAD() Returns the value of expr from the row that leads (follows) the current row by N rows within its partition

As a solution to above problem statement please try executing following SQL query.

SELECT id,name,ini_day,LEAD(ini_day,1) OVER () -1 as end_day
FROM `table`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.