Leetcode 1141. 1142 User Activity for the Past 30 Days

drop table Activity
Create table Activity (user_id int, session_id int, activity_date date, activity_type varchar(20))

insert into Activity (user_id, session_id, activity_date, activity_type) values ('1', '1', '2019-07-20', 'open_session')
insert into Activity (user_id, session_id, activity_date, activity_type) values ('1', '1', '2019-07-20', 'scroll_down')
insert into Activity (user_id, session_id, activity_date, activity_type) values ('1', '1', '2019-07-20', 'end_session')
insert into Activity (user_id, session_id, activity_date, activity_type) values ('2', '4', '2019-07-20', 'open_session')
insert into Activity (user_id, session_id, activity_date, activity_type) values ('2', '4', '2019-07-21', 'send_message')
insert into Activity (user_id, session_id, activity_date, activity_type) values ('2', '4', '2019-07-21', 'end_session')
insert into Activity (user_id, session_id, activity_date, activity_type) values ('3', '2', '2019-07-21', 'open_session')
insert into Activity (user_id, session_id, activity_date, activity_type) values ('3', '2', '2019-07-21', 'send_message')
insert into Activity (user_id, session_id, activity_date, activity_type) values ('3', '2', '2019-07-21', 'end_session')
insert into Activity (user_id, session_id, activity_date, activity_type) values ('4', '3', '2019-06-25', 'open_session')
insert into Activity (user_id, session_id, activity_date, activity_type) values ('4', '3', '2019-06-25', 'end_session')

1141. User Activity for the Past 30 Days I

Write an SQL query to find the daily active user count for a period of 30 days ending 2019-07-27 inclusively. A user was active on some day if he/she made at least one activity on that day.

 

select activity_date as [day]
,count(distinct user_id) as active_users
from Activity
where DATEDIFF(day,activity_date,'2019-07-27')<30
group by activity_date

1142. 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.

 

CTE

with cte1 as(
select count(activity_type) as total
from Activity
where DATEDIFF(day,activity_date,'2019-07-27')<=30
and activity_type in ('scroll_down','send_message')
), cte2 as (select count(distinct user_id) as people
 from Activity
where DATEDIFF(day,activity_date,'2019-07-27')<=30) 
select round(cast(c1.total as float) /cast(c2.people as float),2)
from cte1 c1,cte2 c2 as average_sessions_per_user

General

select round(cast(count(activity_type) as float) /cast(count(distinct user_id) as 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')

 

你可能感兴趣的:(Leetcode 1141. 1142 User Activity for the Past 30 Days)