Search code examples
mysqlsqldatetimegreatest-n-per-groupwindow-functions

Selecting Data from Normalized Tables


I'm stuck on trying to write this query, I think my brain is just a little fried tonight. I have this table that stores whenever a person executes an action (Clocking In, Clocking Out, Going on Lunch, Returning from Lunch) and I need to return a list of all the primary ID's for the people who's last action is not clock_out - but the problem is it needs to be a somewhat fast query.

Table Structure:

ID | person_id | status | datetime | shift_type

ID = Primary Key for this table

person_id = The ID I want to return if their status does not equal clock_out

status = clock_in, lunch_start, lunch_end, break_start, break_end, clock_out

datetime = The time the record was added

shift_type = Not Important

The way I was executing this query before was finding people who are still clocked in during a specific time period, however I need this query to locate at any point. The queries I am trying are taking the thousands and thousands of records and making it way too slow.


Solution

  • After looking through it further, this was my solution -

    SELECT * FROM (
       SELECT `status`,`person_id` FROM `timeclock` ORDER BY `datetime` DESC
    ) AS tmp_table GROUP BY `person_id`
    

    This works because it is grouping all of the same person ID's together, and then ordering them by the datetime and selecting the most recent.