Write an SQL query that reports for every date within at most 90 days from today, the number of users that logged in for the first time on that date. Assume today is 2019-06-30.
Example:
Table: Traffic:+---------+----------+---------------+| user_id | activity | activity_date |+---------+----------+---------------+| 1 | login | 2019-05-01 || 1 | homepage | 2019-05-01 || 1 | logout | 2019-05-01 || 2 | login | 2019-06-21 || 2 | logout | 2019-06-21 || 3 | login | 2019-01-01 || 3 | jobs | 2019-01-01 || 3 | logout | 2019-01-01 || 4 | login | 2019-06-21 || 4 | groups | 2019-06-21 || 4 | logout | 2019-06-21 || 5 | login | 2019-03-01 || 5 | logout | 2019-03-01 || 5 | login | 2019-06-21 || 5 | logout | 2019-06-21 |+---------+----------+---------------+Result:+------------+-------------+| login_date | user_count |+------------+-------------+| 2019-05-01 | 1 || 2019-06-21 | 2 |+------------+-------------+
Approach
Mysql: Using DATEDIFF method
SELECT login_date, COUNT(user_id) user_countFROM(SELECT user_id, MIN(activity_date) as login_dateFROM TrafficWHERE activity='login'GROUP BY user_id) as tWHERE DATEDIFF('2019-06-30', login_date) <= 90GROUP BY login_date
Mysql: Using the DATE_ADD method
SELECT login_date, count(user_id) AS user_countFROM (SELECT user_id, MIN(activity_date) AS login_dateFROM TrafficWHERE activity = 'login'GROUP BY user_id) AS tWHERE login_date >= DATE_ADD('2019-06-30', INTERVAL -90 DAY)AND login_date <= '2019-06-30'GROUP BY login_date;
No comments:
Post a Comment