天天看點

LeetCode MySQL 1141. 查詢近30天活躍使用者數

文章目錄

    • 1. 題目
    • 2. 解題

1. 題目

活動記錄表:Activity

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user_id       | int     |
| session_id    | int     |
| activity_date | date    |
| activity_type | enum    |
+---------------+---------+
該表是使用者在社交網站的活動記錄。
該表沒有主鍵,可能包含重複資料。
activity_type 字段為以下四種值 
('open_session', 'end_session', 'scroll_down', 'send_message')。
每個 session_id 隻屬于一個使用者。           

複制

請寫SQL查詢出截至 2019-07-27(包含2019-07-27),

近 30天的每日活躍使用者數(當天隻要有一條活動記錄,即為活躍使用者)。

查詢結果示例如下:

Activity table:
+---------+------------+---------------+---------------+
| user_id | session_id | activity_date | activity_type |
+---------+------------+---------------+---------------+
| 1       | 1          | 2019-07-20    | open_session  |
| 1       | 1          | 2019-07-20    | scroll_down   |
| 1       | 1          | 2019-07-20    | end_session   |
| 2       | 4          | 2019-07-20    | open_session  |
| 2       | 4          | 2019-07-21    | send_message  |
| 2       | 4          | 2019-07-21    | end_session   |
| 3       | 2          | 2019-07-21    | open_session  |
| 3       | 2          | 2019-07-21    | send_message  |
| 3       | 2          | 2019-07-21    | end_session   |
| 4       | 3          | 2019-06-25    | open_session  |
| 4       | 3          | 2019-06-25    | end_session   |
+---------+------------+---------------+---------------+

Result table:
+------------+--------------+ 
| day        | active_users |
+------------+--------------+ 
| 2019-07-20 | 2            |
| 2019-07-21 | 2            |
+------------+--------------+ 
非活躍使用者的記錄不需要展示。           

複制

來源:力扣(LeetCode)

連結:https://leetcode-cn.com/problems/user-activity-for-the-past-30-days-i

著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。

2. 解題

  • 一個使用者可能有多個 session_id,不能用它去重
  • datediff('2019-07-27', activity_date)

    ,前者減後者的值
# Write your MySQL query statement below
select activity_date day, count(distinct user_id) active_users
from Activity
where datediff('2019-07-27', activity_date) < 30
group by activity_date           

複制

  • date_sub('2019-07-27', interval 30 day)

    ,前者減去30天
# Write your MySQL query statement below
select activity_date day, count(distinct user_id) active_users
from Activity
where activity_date > date_sub('2019-07-27', interval 30 day)
group by activity_date           

複制