Active Users

Write an SQL query to find the id and the name of active users.
Active users are those who logged in to their accounts for 5 or more consecutive days.

Example:


Table: Accounts
+----+----------+
| id | name     |
+----+----------+
1  | Winston  |
7  | Jonathan |
+----+----------+

Table: Logins
+----+------------+
| 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 |
+----+------------+

Result:
+----+----------+
| id | name     |
+----+----------+
7  | Jonathan |
+----+----------+

Approach

Mysql

SELECT  * FROM Accounts
WHERE id IN
    (SELECT distinct t1.id
    FROM Logins as t1 INNER JOIN Logins as t2
    on t1.id = t2.id and datediff(t1.login_date, t2.login_date) BETWEEN 1 AND 4
    GROUP BY t1.id, t1.login_date
    HAVING count(distinct(t2.login_date)) = 4)
ORDER BY id;


No comments:

Post a Comment