Search code examples
sqlsql-server-2016

SQL Group attendance list by user and time


I have list of users on site

User In Out
User 1 31.10.2023 04:20
User 1 31.10.2023 05:20
User 1 31.10.2023 05:25
User 2 31.10.2023 02:20
User 3 31.10.2023 03:00
User 3 31.10.2023 05:20
User 3 31.10.2023 05:21

I want to get the result list with users who are on Site

User In
User 1 31.10.2023 05:25
User 2 31.10.2023 02:20

Please help with SQL query.


Solution

  • Group by each user and select only those having a higher IN than OUT which means they are still in.

    select user_name, max(in_time)
    from your_table
    group by user_name
    having max(in_time) > max(out_time)