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.
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