Project: course report

Combine joins, CTEs, windows and CASE in a reusable reporting query.

Beginner 25 min read Lesson 16 of 480 Challenge included
What you will be able to do
  • Join and aggregate in a CTE
  • Rank the result with a window
  • Label depth with CASE

A reporting query answers a real question: which courses are deepest, and how do they rank? Build it in layers so each step can be checked.

  1. 01
    Total per course

    LEFT JOIN courses to lessons and aggregate lessons and minutes.

  2. 02
    Rank

    Number the courses by total minutes, highest first.

  3. 03
    Label

    Use CASE to describe the depth band.

  4. 04
    Check

    Compare the totals with a simple GROUP BY before trusting the report.

report.sqlSQL
WITH course_totals AS (
  SELECT c.title,
         COUNT(l.id) AS lessons,
         COALESCE(SUM(l.minutes), 0) AS minutes
  FROM courses c
  LEFT JOIN lessons l ON l.course_slug = c.slug
  GROUP BY c.id, c.title
),
ranked AS (
  SELECT *,
         ROW_NUMBER() OVER (ORDER BY minutes DESC) AS rank
  FROM course_totals
)
SELECT rank, title, lessons, minutes,
       CASE
         WHEN minutes >= 45 THEN 'Deep'
         WHEN minutes >= 30 THEN 'Solid'
         ELSE 'Starter'
       END AS depth
FROM ranked
ORDER BY rank;
Your turn

Add average minutes and filter

Hard

Extend the report with average minutes per lesson and return only courses with at least two lessons.

SQL · starter
WITH course_totals AS (
  SELECT c.title,
         COUNT(l.id) AS lessons,
         COALESCE(SUM(l.minutes), 0) AS minutes
  FROM courses c
  LEFT JOIN lessons l ON l.course_slug = c.slug
  GROUP BY c.id, c.title
)
Check your understanding before moving on.
Knowledge checkQuestion 1

Which construct names a reusable result set inside a single query?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 16 of 480 · 0% of course