63. Latest 2020 Login
You are building a user activity dashboard and want to identify the most recent login for each user.
You are given a Logins table.
βββββββββββββββ¦βββββββββββ β Column Name β Type β β ββββββββββββββ¬βββββββββββ£ β user_id β int β βββββββββββββββΌβββββββββββ β time_stamp β datetime β βββββββββββββββ©βββββββββββ
- user_id: The ID of the user who logged in
- time_stamp: The exact date and time the user logged in
- The combination of (user_id, time_stamp) acts as the primary key.
- A user can have multiple logins. No two login entries for the same user will have the same timestamp.
Write a query to find the most recent login date in the year 2020 for each user. Exclude users who didn't log in during 2020. The result can be returned in any order.
Example 1:
Example:
Input:
Logins Table
βββββββββββ¦ββββββββββββββββββββββ β user_id β time_stamp β β ββββββββββ¬ββββββββββββββββββββββ£ β 6 β 2020-06-30 15:06:07 β βββββββββββΌββββββββββββββββββββββ β 6 β 2021-04-21 14:06:06 β βββββββββββΌββββββββββββββββββββββ β 6 β 2019-03-07 00:18:15 β βββββββββββΌββββββββββββββββββββββ β 8 β 2020-02-01 05:10:53 β βββββββββββΌββββββββββββββββββββββ β 8 β 2020-12-30 00:46:50 β βββββββββββΌββββββββββββββββββββββ β 2 β 2020-01-16 02:49:50 β βββββββββββΌββββββββββββββββββββββ β 2 β 2019-08-25 07:59:08 β βββββββββββΌββββββββββββββββββββββ β 14 β 2019-07-14 09:00:00 β βββββββββββΌββββββββββββββββββββββ β 14 β 2021-01-06 11:59:59 β βββββββββββ©ββββββββββββββββββββββ
Expected Output:
βββββββββββ¦ββββββββββββββββββββββ β user_id β last_stamp β β ββββββββββ¬ββββββββββββββββββββββ£ β 2 β 2020-01-16 02:49:50 β βββββββββββΌββββββββββββββββββββββ β 6 β 2020-06-30 15:06:07 β βββββββββββΌββββββββββββββββββββββ β 8 β 2020-12-30 00:46:50 β βββββββββββ©ββββββββββββββββββββββ
Explanation:
We only consider logins from 2020 and pick the latest one for each user:
- User 6 β Latest in 2020: 2020-06-30
- User 8 β Latest in 2020: 2020-12-30
- User 2 β Only 2020 login: 2020-01-16
- User 14 β No 2020 login (Excluded)
Still unsure what the problem is asking ?
Letβs go through a few more examples, step by step, to make it clearer.