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.

Hints

0
Β 
Test Case

Input:

Logins