Calculate average session length per daily active user?

tinatodoroki :

I'm pretty new to SQL and I'm struggling with one of the questions on my exercise. How would I calculate average session length per daily active user? The table shown is just a sample of what the extended table is. Imagine loads more rows.

I simply used this query to calculate the daily active users:

SELECT COUNT (DISTINCT user_id) 
FROM table1
balexandre :

and welcome to StackOverflow!

now, your question:

How would I calculate average session length per daily active user?

you already have the session time, and using AVG function you will get a simple average for all

select AVG(session_length_seconds) avg from table_1

but you want per day... so you need to think as group by day, so how do you get the day? you have a activity_date as a Date entry, it's easy to extract day, month and year from it, for example

select
    DAY(activity_date) day,
    MONTH((activity_date) month,
    YEAR(activity_date) year
from
    table_1

will break down the date field in columns you can use...

now, back to your question, it states daily active user, but all you have is sessions, a user could have multiple sessions, so I have no idea, from the context you have shared, how you go about that, and make the avg for each session, makes no sense as data to retrieve, I'll just assume, and serves this answer just to get you started, that you want the avg per day only

knowing how to get the average, let's create a query that has it all together:

select 
    DAY(activity_date) day, 
    MONTH((activity_date) month, 
    YEAR(activity_date) year,
    AVG(session_length_seconds) avg 
from 
    table_1
group by
    DAY(activity_date), 
    MONTH((activity_date), 
    YEAR(activity_date)

will output the average of session_length_seconds per day/month/year

the group by part, you need to have as many fields you have in the select but that do not do any calculation, like sum, count, etc... in our case avg does calculation, so we don't want to group by that value, but we do want to group by the other 3 values, so we have a 3 columns with day, month and year. You can also use concat to join day, month and year into just one string if you prefer...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=193498&siteId=1