The Latest Login in 2020 - Problem

You are given a table Logins that contains information about user login times.

Write a SQL query to find the latest login for each user in the year 2020. Do not include users who did not login in 2020.

Return the result table in any order.

Table Schema

Logins
Column Name Type Description
user_id PK int User identifier
time_stamp PK datetime Login timestamp
Primary Key: (user_id, time_stamp)
Note: Each row represents a login event for a specific user

Input & Output

Example 1 — Multiple Users with Multiple Logins
Input Table:
user_id time_stamp
1 2020-01-01 10:00:00
1 2020-12-30 17:30:00
2 2020-10-12 14:00:00
3 2019-06-30 09:00:00
3 2021-04-21 15:00:00
Output:
user_id last_stamp
1 2020-12-30
2 2020-10-12
💡 Note:

User 1 had two logins in 2020, we return the latest one (2020-12-30). User 2 had one login in 2020. User 3 had no logins in 2020, so they are excluded from the result.

Example 2 — Single Login Per User
Input Table:
user_id time_stamp
5 2020-03-15 08:30:00
7 2020-07-20 12:45:00
Output:
user_id last_stamp
5 2020-03-15
7 2020-07-20
💡 Note:

Each user has only one login in 2020, so that single login is their latest (and only) login for the year.

Example 3 — No 2020 Logins
Input Table:
user_id time_stamp
10 2019-12-31 23:59:59
11 2021-01-01 00:00:01
Output:
user_id last_stamp
💡 Note:

No users had any logins during 2020, so the result is empty. All logins were either before 2020 or after 2020.

Constraints

  • 1 ≤ user_id ≤ 10^4
  • time_stamp is a valid datetime
  • The table may contain multiple login records for the same user

Visualization

Tap to expand
The Latest Login in 2020 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-01-17 22:11:17 8 2020-08-24 08:11:17 2 2020-01-16 02:49:50 14 2019-05-16 01:42:50 Filter: Only 2020 logins YEAR(time_stamp) = 2020 ALGORITHM STEPS 1 Filter Year 2020 WHERE YEAR(time_stamp) = 2020 2 Group by user_id GROUP BY user_id to process each user 3 Find MAX timestamp MAX(time_stamp) for latest login per user 4 Return Results Output user_id and last_login columns SELECT user_id, MAX(time_stamp) FROM Logins WHERE YEAR(...)=2020 FINAL RESULT user_id last_login 6 2020-06-30 8 2020-08-24 2 2020-01-16 OK User 14 excluded: No login in 2020 User 6: 2021 login excluded (not 2020) Key Insight: Use WHERE with YEAR() function to filter timestamps for 2020 only, then GROUP BY user_id with MAX(time_stamp) to find each user's latest login. Users without 2020 logins are auto-excluded. TutorialsPoint - The Latest Login in 2020 | Optimal Solution: WHERE + GROUP BY + MAX
Asked in
Facebook 28 Amazon 22 Microsoft 18
28.5K Views
Medium Frequency
~8 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen