-
Notifications
You must be signed in to change notification settings - Fork 0
/
Biggest Window Between Visits 26-10-22
82 lines (58 loc) · 2.52 KB
/
Biggest Window Between Visits 26-10-22
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
link ---------- https://www.codingninjas.com/codestudio/problems/biggest-window-between-visits_2181136?topList=top-100-sql-problems
Problem Statement
able: UserVisits
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id | int |
| visit_date | date |
+-------------+------+
This table does not have a primary key.
This table contains logs of the dates that users vistied a certain retailer.
Assume today's date is '2021-1-1'.
Write an SQL query that will, for each user_id, find out the largest window of days between each visit and the one right after it (or today if you are considering the last visit).
Return the result table ordered by user_id.
The query result format is in the following example:
UserVisits table:
+---------+------------+
| user_id | visit_date |
+---------+------------+
| 1 | 2020-11-28 |
| 1 | 2020-10-20 |
| 1 | 2020-12-3 |
| 2 | 2020-10-5 |
| 2 | 2020-12-9 |
| 3 | 2020-11-11 |
+---------+------------+
Result table:
+---------+---------------+
| user_id | biggest_window|
+---------+---------------+
| 1 | 39 |
| 2 | 65 |
| 3 | 51 |
+---------+---------------+
For the first user, the windows in question are between dates:
- 2020-10-20 and 2020-11-28 with a total of 39 days.
- 2020-11-28 and 2020-12-3 with a total of 5 days.
- 2020-12-3 and 2021-1-1 with a total of 29 days.
Making the biggest window the one with 39 days.
For the second user, the windows in question are between dates:
- 2020-10-5 and 2020-12-9 with a total of 65 days.
- 2020-12-9 and 2021-1-1 with a total of 23 days.
Making the biggest window the one with 65 days.
For the third user, the only window in question is between dates 2020-11-11 and 2021-1-1 with a total of 51 days.
------------------------------- solution ----------------------------------
select user_id, max(abs(biggest)) biggest_window from
(select user_id , visit_date - lag(visit_date,1,'2021-1-1') over (partition by user_id order by visit_date desc) as biggest
from uservisits ) as x
group by 1
--------------------------------- solution 2 ---------------------------------
select w.user_id, max(w.diffs) as biggest_window from
(
select user_id, visit_date,
COALESCE(lead(visit_date) OVER(partition by user_id ORDER BY visit_date),'2021-1-1') AS next_date,
COALESCE(lead(visit_date) OVER(partition by user_id ORDER BY visit_date),'2021-1-1'):: DATE - visit_date:: DATE as diffs
from UserVisits
) w
group by 1;