sql >> Base de Datos >  >> RDS >> Mysql

Mysql Foreach de una tabla a otra Parte 2

Parece que está buscando agregación condicional:

select 
    u.user_id,
    u.username,
    min(case when a.action = 'IN' then a.dateTime end) `in`,
    max(case when a.action = 'OUT' then a.dateTime end) `out`
from 
    user u
    inner join user_attendance a on u.user_id = a.user_id
group by
    u.user_id,
    u.username,
    date(a.dateTime)
order by
    u.user_id,
    date(a.dateTime)

Demostración en DB Fiddle :

| user_id | username | in                  | out                 |
| ------- | -------- | ------------------- | ------------------- |
| 1       | tiger    | 2019-10-01 08:00:00 | 2019-10-01 14:00:00 |
| 1       | tiger    | 2019-10-02 08:00:00 | 2019-10-02 14:00:00 |
| 2       | pooh     | 2019-10-01 08:00:00 | 2019-10-01 14:00:00 |
| 2       | pooh     | 2019-10-02 08:00:00 | 2019-10-02 14:00:00 |