返回介绍

solution / 1400-1499 / 1454.Active Users / README_EN

发布于 2024-06-17 01:03:19 字数 2870 浏览 0 评论 0 收藏 0

1454. Active Users

中文文档

Description

Table: Accounts

+---------------+---------+
| Column Name   | Type  |
+---------------+---------+
| id      | int   |
| name      | varchar |
+---------------+---------+
id is the primary key (column with unique values) for this table.
This table contains the account id and the user name of each account.

 

Table: Logins

+---------------+---------+
| Column Name   | Type  |
+---------------+---------+
| id      | int   |
| login_date  | date  |
+---------------+---------+
This table may contain duplicate rows.
This table contains the account id of the user who logged in and the login date. A user may log in multiple times in the day.

 

Active users are those who logged in to their accounts for five or more consecutive days.

Write a solution to find the id and the name of active users.

Return the result table ordered by id.

The result format is in the following example.

 

Example 1:

Input: 
Accounts table:
+----+----------+
| id | name   |
+----+----------+
| 1  | Winston  |
| 7  | Jonathan |
+----+----------+
Logins table:
+----+------------+
| id | login_date |
+----+------------+
| 7  | 2020-05-30 |
| 1  | 2020-05-30 |
| 7  | 2020-05-31 |
| 7  | 2020-06-01 |
| 7  | 2020-06-02 |
| 7  | 2020-06-02 |
| 7  | 2020-06-03 |
| 1  | 2020-06-07 |
| 7  | 2020-06-10 |
+----+------------+
Output: 
+----+----------+
| id | name   |
+----+----------+
| 7  | Jonathan |
+----+----------+
Explanation: 
User Winston with id = 1 logged in 2 times only in 2 different days, so, Winston is not an active user.
User Jonathan with id = 7 logged in 7 times in 6 different days, five of them were consecutive days, so, Jonathan is an active user.

 

Follow up: Could you write a general solution if the active users are those who logged in to their accounts for n or more consecutive days?

Solutions

Solution 1

# Write your MySQL query statement below
WITH t AS
  (SELECT *,
     SUM(id) over(partition by id
  ORDER BY  login_date range interval 4 day preceding)/id cnt
  FROM
    (SELECT DISTINCT *
    FROM Accounts
    JOIN Logins using(id) ) tt )
  SELECT DISTINCT id,
     name
FROM t
WHERE cnt=5;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文