SQL Practice: Grouping Web Sessions by Channel
A second fresh dataset: put GROUP BY, COUNT, and AVG to work on marketing traffic.
This chapter swaps the shop for the marketing analytics dataset you met briefly in Lesson 5.5: users, campaigns, sessions, pageviews, and events for a SaaS website. It is the classic shape of data an analyst works with every day.
The
sessions
table has one row per visit, each tagged with a
channel
(organic, paid, social, email, direct) and a
duration_seconds. "Which channels drive the most traffic?" is a grouping question.
Count and average in one pass
Grouping by
channel
collapses every visit into one row per channel. From there,
count(*)
measures volume and
avg(duration_seconds)
measures engagement. They are two very different questions answered by the
same grouped query.
select group_column,
count(*) as row_count,
round(avg(number_column), 1) as average
from table_name
group by group_column
order by row_count desc, group_column Schema · Website Analytics Table · sessions 7 columns · 30 rows
One row per visit. Anonymous visits have a null user_id; organic and direct visits have a null campaign_id.
For each channel, return the channel, the number of sessions (sessions), and the average duration in seconds rounded to one decimal (avg_seconds). Sort by sessions descending, then channel.
Run your query to inspect the result.
Expected answer
- Columns: channel, sessions, avg_seconds.
- Rows: 5 channels.
- Organic leads with 10 sessions and a 314.4-second average.
Related
COUNT, SUM, AVG, MIN, MAX, GROUP BY, and HAVING.
COUNT, SUM, AVG, GROUP BY, and HAVING.
Practice aggregate reports, HAVING, and answer shape.
Avoid truncating fractional results.
Group or aggregate every selected column.
Practice buckets, business labels, and conditional counts.