User Activity for the Past 30 Days II

Write an SQL query to find the average number of sessions per user for a period of 30 days ending 2019-07-27 inclusively, rounded to 2 decimal places. The sessions we want to count for a user are those with at least one activity in that time period.


Table: Activity

+---------+------------+---------------+---------------+
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   |
3       | 5          | 2019-07-21    | open_session  |
3       | 5          | 2019-07-21    | scroll_down   |
3       | 5          | 2019-07-21    | end_session   |
4       | 3          | 2019-06-25    | open_session  |
4       | 3          | 2019-06-25    | end_session   |
+---------+------------+---------------+---------------+

Result:
+---------------------------+ 
| average_sessions_per_user |
+---------------------------+ 
1.33                      |
+---------------------------+ 


Approach

Oracle

select round(cast(count(activity_type) as float) /
    cast(count(distinct user_idas float),2
as average_sessions_per_user
from Activity 
where ((TO_DATE('2019-07-27','YYYY-MM-DD')-activity_date))<=30
and activity_type in ('scroll_down','send_message')

Mysql

select round(cast(count(activity_type) as float) /
    cast(count(distinct user_idas float),2
as average_sessions_per_user
from Activity 
where DATEDIFF(day,activity_date,'2019-07-27')<=30
and activity_type in ('scroll_down','send_message')


No comments:

Post a Comment