Hello!
I have a table with the following structure:
id | fecha_inicio
---+--------------------
10 | 2016-12-01 10:15:00
10 | 2016-12-03 16:02:00
11 | 2016-12-02 11:23:00
I want to build a query that has the start and the end of the period, where, for example, the end date of the first period of the id 10
is 2016-12-03 16:02:00
. The result I'm looking for is something like the following:
id | fecha_inicio | fecha_final
---+---------------------+--------------------
10 | 2016-12-01 10:15:00 | 2016-12-03 16:02:00
10 | 2016-12-03 16:02:00 | NULL
11 | 2016-12-02 11:23:00 | NULL
Is there a way to build this query using only SQL expressions? I know that it is possible to build it using other languages, but it would be much easier for me to do it directly in the database.
Cheers
I've been giving the idea some thought, and I think I've found the solution: Use user variables:
id
ascending, and byfecha
descending , to be able to "drag" the value offecha
.case
checks if theid
current record is the same as theid
previous record (which is in the variable@id_ant
):id
is equal to the value of@id_ant
, then put the value of@f_ini
(which is updated on each row with the value offecha
);id
not the same as the value of@id_ant
, then put aNULL
.@id_ant
and@f_ini
, so you can use them in the next row.The result looked like this (I used [SQL Fiddle][ http://sqlfiddle.com/#!9/e4522] to make the problem reproducible; I added a few more values to make the example clearer):
SQL-Fiddle
MySQL 5.6 Schema Setup :
Query 1 :
Results :
Query 2 :
Results :
Query 3 :
Results :
It can also be achieved using
MIN()
in a sub-query:Demo
Demo 2