-
Notifications
You must be signed in to change notification settings - Fork 43
/
get-the-second-most-recent-activity.sql
91 lines (77 loc) · 2.64 KB
/
get-the-second-most-recent-activity.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
SQL Schema
Table: UserActivity
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| username | varchar |
| activity | varchar |
| startDate | Date |
| endDate | Date |
+---------------+---------+
This table does not contain primary key.
This table contain information about the activity performed of each user in a period of time.
A person with username performed a activity from startDate to endDate.
Write an SQL query to show the second most recent activity of each user.
If the user only has one activity, return that one.
A user can’t perform more than one activity at the same time. Return the result table in any order.
The query result format is in the following example:
UserActivity table:
+------------+--------------+-------------+-------------+
| username | activity | startDate | endDate |
+------------+--------------+-------------+-------------+
| Alice | Travel | 2020-02-12 | 2020-02-20 |
| Alice | Dancing | 2020-02-21 | 2020-02-23 |
| Alice | Travel | 2020-02-24 | 2020-02-28 |
| Bob | Travel | 2020-02-11 | 2020-02-18 |
+------------+--------------+-------------+-------------+
Result table:
+------------+--------------+-------------+-------------+
| username | activity | startDate | endDate |
+------------+--------------+-------------+-------------+
| Alice | Dancing | 2020-02-21 | 2020-02-23 |
| Bob | Travel | 2020-02-11 | 2020-02-18 |
+------------+--------------+-------------+-------------+
The most recent activity of Alice is Travel from 2020-02-24 to 2020-02-28, before that she was dancing from 2020-02-21 to 2020-02-23.
Bob only has one record, we just take that one.
*/
# V0
# V1
# https://code.dennyzhang.com/get-the-second-most-recent-activity
(select *
from UserActivity
group by username
having count(1) = 1)
union
(select a.*
from UserActivity as a left join UserActivity as b
on a.username = b.username and a.endDate < b.endDate
group by a.username, a.endDate
having count(b.endDate) = 1)
# V2
# Time: O(nlogn)
# Space: O(n)
SELECT *
FROM UserActivity
GROUP BY username
HAVING COUNT(1) = 1
UNION ALL
SELECT a.username,
a.activity,
a.startDate,
a.endDate
FROM
(SELECT @accu := (CASE
WHEN username = @prev THEN @accu + 1
ELSE 1
END) AS n,
@prev := username AS username,
activity,
startDate,
endDate
FROM
(SELECT @accu := 0, @prev := 0) AS init,
UserActivity AS u
ORDER BY username,
endDate DESC) AS a
WHERE n = 2;