首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >LeetCode MySQL 1141. 查询近30天活跃用户数

LeetCode MySQL 1141. 查询近30天活跃用户数

作者头像
Michael阿明
发布于 2021-02-19 09:57:16
发布于 2021-02-19 09:57:16
1.4K0
举报

文章目录

1. 题目

活动记录表:Activity

代码语言:javascript
复制
+---------------+---------+
| 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天的每日活跃用户数(当天只要有一条活动记录,即为活跃用户)。

代码语言:javascript
复制
查询结果示例如下:

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),前者减后者的值
代码语言:javascript
复制
# 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天
代码语言:javascript
复制
# 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
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/07/18 ,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 文章目录
  • 1. 题目
  • 2. 解题
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档