+—————-+———-+
| Column Name | Type |
+—————-+———-+
| user_id | int |
| time_stamp | datetime |
+—————-+———-+
(user_id, time_stamp) is the primary key (combination of columns with unique values) for this table.
Each row contains information about the login time for the user with ID user_id.
Write a solution to report the latest login for all users in the year
2020. Do not include the users who did not login in 2020.
Input:
Logins table:+---------+---------------------+| user_id | time_stamp |+---------+---------------------+|6|2020-06-3015:06:07||6|2021-04-2114:06:06||6|2019-03-0700:18:15||8|2020-02-0105:10:53||8|2020-12-3000:46:50||2|2020-01-1602:49:50||2|2019-08-2507:59:08||14|2019-07-1409:00:00||14|2021-01-0611:59:59|+---------+---------------------+Output:
+---------+---------------------+| user_id | last_stamp |+---------+---------------------+|6|2020-06-3015:06:07||8|2020-12-3000:46:50||2|2020-01-1602:49:50|+---------+---------------------+Explanation:
User 6 logged into their account 3 times but only once in2020, so we include this login in the result table.User 8 logged into their account 2 times in2020, once in February and once in December. We include only the latest one(December)in the result table.User 2 logged into their account 2 times but only once in2020, so we include this login in the result table.User 14 did not login in2020, so we do not include them in the result table.## Solution
### Method 1- SQL (MySQL, PostgreSQL, Oracle)We filter logins to only those in2020, then group by user and select the latest timestamp for each user.#### Code
1
2
3
4
SELECT user_id, MAX(time_stamp) AS last_stamp
FROM Logins
WHEREYEAR(time_stamp) =2020GROUPBY user_id;
1
2
3
4
SELECT user_id, MAX(time_stamp) AS last_stamp
FROM Logins
WHEREEXTRACT(YEARFROM time_stamp) =2020GROUPBY user_id;
1
2
3
4
SELECT user_id, MAX(time_stamp) AS last_stamp
FROM Logins
WHEREEXTRACT(YEARFROM time_stamp) =2020GROUPBY user_id;
#### Explanation
- We filter logins to only those in2020 using the appropriate date functionfor each SQL dialect.- We group by user and select the latest timestamp for each user.- Only users who logged in during 2020 are included.#### Complexity
-⏰ Time complexity:`O(N)` where N is the number of logins.-🧺 Space complexity:`O(U)` where U is the number of unique users logging in2020.