当前位置:网站首页>Database daily question --- day 22: last login

Database daily question --- day 22: last login

2022-07-07 23:00:00 InfoQ


One 、 Problem description

surface
: 
Logins

+----------------+----------+
|  Name  |  type  |
+----------------+----------+
| user_id | int |
| time_stamp | datetime |
+----------------+----------+
(user_id, time_stamp)  It's the primary key of this table .
The information contained in each line is user_id  The login time of this user .

Write a  
SQL
  Inquire about , The query can be obtained in  
2020
  Current year of all users logged in in   The last time  
The login time
. Result set   No   contain  
2020
  Users who haven't logged in in years .

The returned result set can be  
In any order
  array .

Query results
The format is as follows :

Topic link
Last login

Two 、 Subject requirements

Examples

Input :
Logins  surface :
+---------+---------------------+
| 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 |
+---------+---------------------+
Output :
+---------+---------------------+
| user_id | last_stamp |
+---------+---------------------+
| 6 | 2020-06-30 15:06:07 |
| 8 | 2020-12-30 00:46:50 |
| 2 | 2020-01-16 02:49:50 |
+---------+---------------------+
explain :
6 User number is logged in 3 Time , But in 2020 Only once a year , Therefore, the result set should include this login .
8 User number is 2020 Logged in in 2 Time , Once in 2 month , Once in 12 month , therefore , The result set should contain 12 This login in June .
2 User number is logged in 2 Time , But in 2020 Only once a year , Therefore, the result set should include this login .
14 User number is 2020 I didn't log in in , Therefore, the result set should not contain .

Investigate

1. Aggregate functions
2. It is recommended to use time 10~25min

3、 ... and 、 Problem analysis

The title requires us to find
2020
Last logged in user in , Among them, users may log in several times in a year , We just need to find out
2020
Maximum date of the year .

For this question , Grouping aggregate functions can still solve the problem , We group by user number , Each number data after grouping contains the date of login , That's when we use
max
Function directly solves the maximum date .

Four 、 coded

select user_id, max(time_stamp) as 'last_stamp'
from Logins
where year(time_stamp)=2020
group by user_id

5、 ... and 、 test result

null
null
null
原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207072008171941.html