Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MySQL: Select and calculate values from next row

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading