"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Retrieve the Latest Login Date for Each User in SQL?

How to Retrieve the Latest Login Date for Each User in SQL?

Posted on 2025-02-06
Browse:411

How to Retrieve the Latest Login Date for Each User in SQL?

SQL query for the last login record date for each user

question:

Suppose the database table contains user login information, how do we retrieve the last login date for each user? Considering that there may be duplicate login dates.

Solution:

There are two common ways to solve this problem:

Method 1: Subquery using INNER JOIN

This method uses a subquery to identify the last login date for each user and is then used to filter the main table:

select t.username, t.date, t.value
from MyTable t
inner join (
    select username, max(date) as MaxDate
    from MyTable
    group by username
) tm on t.username = tm.username and t.date = tm.MaxDate

Method 2: Window function

]

For databases that support window functions, a more efficient method can be used:

select x.username, x.date, x.value 
from (
    select username, date, value,
        row_number() over (partition by username order by date desc) as _rn
    from MyTable 
) x
where x._rn = 1

This method uses row numbers sorting on partition data, where the last date of each user is assigned a level 1.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3