I have a table in MySQL as following:
+----+--------+------------------+------+
| id | userid | fecha_ingreso | tipo |
+----+--------+------------------+------+
| 1 | 1 | 2015-06-08 20:00 | 1 |
| 3 | 1 | 2015-06-09 05:00 | 2 |
| 18 | 2 | 2015-06-09 23:30 | 1 |
| 19 | 2 | 2015-06-10 05:00 | 2 |
| 20 | 2 | 2015-06-10 06:00 | 1 |
| 21 | 2 | 2015-06-10 09:00 | 2 |
| 22 | 1 | 2015-06-09 23:30 | 1 |
| 23 | 1 | 2015-06-10 05:00 | 2 |
| 24 | 1 | 2015-06-10 06:00 | 1 |
| 25 | 1 | 2015-06-10 09:00 | 2 |
+----+--------+------------------+------+
10 rows in set
This table has information of every user (userid
) who into the work and out of the work (fecha_ingreso
). For example with userid=1
has enter (tipo=1
) at '2015-06-08 20:00'
and hes left the job at '2015-06-09 05:00'
.
Then I have the userid=2
who is entered (tipo=1
) to job at '2015-06-09 23:30'
(nighttime) and he left (tipo=2
) job for breakfast at '2015-06-10 05:00'
and he entered again at '2015-06-10 06:00'
and he finally left job at '2015-06-10 09:00'
.
I'm not able to make a query that only shows me something like this:
+--------+------+---------------------+---------------------+-----------------+
| userid | INS | OUTS | time_after_22pm_and_lessOrEqual6am |
+--------+------+---------------------+---------------------+-----------------+
| 1 | 2015-06-25 15:00:00 | 2015-06-26 23:15:00| 01:15:00
| 2 | 2015-06-25 23:00:00 | 2015-06-26 13:30:00| 07:00:00
+--------+------+---------------------+---------------------+-----------------+
2 rows in set
This is the output I need. Even when a user can have several ins and outs, I need to show his first entrance datetime and the last out datetime with an aditional column saying how many hours and minutes and seconds hes been at work on range from 22:00 and 6am next day.
Tim, Your query is perfect but it's almost close. However I don't know how to get the hour: minute: secs when a user has been after 22pm (as my sample shows).