You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/3000-3099/3089.Find Bursty Behavior/README_EN.md
+62-1
Original file line number
Diff line number
Diff line change
@@ -75,12 +75,73 @@ Each row of this table contains post_id, user_id, and post_date.
75
75
76
76
## Solutions
77
77
78
-
### Solution 1
78
+
### Solution 1: Self-Join + Group Count
79
+
80
+
We can use self-join to connect the `Posts` table with itself. The connection condition is `p1.user_id = p2.user_id` and `p2.post_date` is between `p1.post_date` and 6 days after `p1.post_date`. Then we group the connection results by `p1.user_id` and `p1.post_date` to count the number of posts for each user within 7 days of each day. We save this result in table `P`.
81
+
82
+
Next, we count the average number of posts per week for each user in February 2024 and save it in table `T`. Note that we need to find records where `post_date` is between `2024-02-01` and `2024-02-28`, group the records by `user_id`, then count the number of posts for each user, and finally divide by `4` to get the average number of posts per week. We save this result in table `T`.
83
+
84
+
Finally, we connect tables `P` and `T` with the condition `P.user_id = T.user_id`, then group by `user_id` to count the maximum number of posts within 7 days for each user. We then filter out records that meet the condition `max_7day_posts >= avg_weekly_posts * 2` to get the result. Note that we need to sort in ascending order by `user_id`.
79
85
80
86
<!-- tabs:start -->
81
87
82
88
```sql
89
+
# Write your MySQL query statement below
90
+
WITH
91
+
P AS (
92
+
SELECTp1.user_idAS user_id, COUNT(1) AS cnt
93
+
FROM
94
+
Posts AS p1
95
+
JOIN Posts AS p2
96
+
ONp1.user_id=p2.user_id
97
+
ANDp2.post_date BETWEEN p1.post_dateAND DATE_ADD(p1.post_date, INTERVAL 6 DAY)
98
+
GROUP BYp1.user_id, p1.post_date
99
+
),
100
+
T AS (
101
+
SELECT user_id, COUNT(1) /4AS avg_weekly_posts
102
+
FROM Posts
103
+
WHERE post_date BETWEEN '2024-02-01'AND'2024-02-28'
104
+
GROUP BY1
105
+
)
106
+
SELECT user_id, MAX(cnt) AS max_7day_posts, avg_weekly_posts
0 commit comments