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

活动记录表:Activity

  1. +---------------+---------+
  2. | Column Name | Type |
  3. +---------------+---------+
  4. | user_id | int |
  5. | session_id | int |
  6. | activity_date | date |
  7. | activity_type | enum |
  8. +---------------+---------+
  9. 该表是用户在社交网站的活动记录。
  10. 该表没有主键,可能包含重复数据。
  11. activity_type 字段为以下四种值 ('open_session', 'end_session', 'scroll_down', 'send_message')。
  12. 每个 session_id 只属于一个用户。

请写SQL查询出截至 2019-07-27(包含2019-07-27),近 30天的每日活跃用户数(当天只要有一条活动记录,即为活跃用户)。

查询结果示例如下:

  1. Activity table:
  2. +---------+------------+---------------+---------------+
  3. | user_id | session_id | activity_date | activity_type |
  4. +---------+------------+---------------+---------------+
  5. | 1 | 1 | 2019-07-20 | open_session |
  6. | 1 | 1 | 2019-07-20 | scroll_down |
  7. | 1 | 1 | 2019-07-20 | end_session |
  8. | 2 | 4 | 2019-07-20 | open_session |
  9. | 2 | 4 | 2019-07-21 | send_message |
  10. | 2 | 4 | 2019-07-21 | end_session |
  11. | 3 | 2 | 2019-07-21 | open_session |
  12. | 3 | 2 | 2019-07-21 | send_message |
  13. | 3 | 2 | 2019-07-21 | end_session |
  14. | 4 | 3 | 2019-06-25 | open_session |
  15. | 4 | 3 | 2019-06-25 | end_session |
  16. +---------+------------+---------------+---------------+
  17. Result table:
  18. +------------+--------------+
  19. | day | active_users |
  20. +------------+--------------+
  21. | 2019-07-20 | 2 |
  22. | 2019-07-21 | 2 |
  23. +------------+--------------+
  24. 非活跃用户的记录不需要展示。

/

  1. select
  2. activity_date day,
  3. count(distinct user_id ) active_users
  4. from
  5. Activity
  6. group by
  7. activity_date
  8. having
  9. datediff('2019-07-27',activity_date )<30

为什么是<30而不是等于,因为包含07-27,所以除了今天还有29天。如果不包含27号就是等于30了

  1. select activity_date day, count(distinct user_id) active_users
  2. from activity
  3. where activity_date > date_sub('2019-07-27', interval 30 day)
  4. and activity_date <= '2019-07-27'
  5. group by activity_date