I have a query which has a GROUP BY
clause. This query takes employees "checkin" times from a records
table and if the dn
field on is 1 then the employee is in the office, but if it's 2, then he/she left.
So lets say I put records.dn
in the GROUP BY
clause. This results with duplicate entries for each employee (I get their names one after the other in a table, twice).
I tried using MIN and MAX in the select, but that didn't make sense at all.
So from those multiple rows in the database where an employee might checkin and out multiple times, how do I take the LATEST row and use its dn
field?
This is the query I'm talking about:
select
MAX(records.dn),
`records`.`din`,
`users`.`username`,
`users`.`id` as `user_id`,
DATE(records.created_at) AS date,
TIME(MIN(records.created_at)) AS first_log,
TIME(MAX(records.created_at)) AS last_log
from `records`
inner join `users` on `records`.`din` = `users`.`din`
where records.created_at BETWEEN '2016-09-05 00:00:00'
AND '2016-09-08 00:00:00'
group by `users`.`username`, DATE(records.created_at)
order by `first_log` asc
(The first select column is what I tried to do, using MAX)
This is the records table with some sample data:
How do I achieve what I'm looking for?