Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Mysql Foreach de uma tabela para outra Parte 2


Parece que você está procurando agregação 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)

Demonstração no 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 |