Applying SQL Aggregate Functions to Multiple Tables
Introduction
Welcome back! In this lesson, we're going to dive into SQL aggregate functions on multiple tables. This lesson will combine everything you have learned so far about SQL queries.
Let's get started putting everything you've learned together.
Dataset Review
For convenience, the tables and columns in our Marvel movies dataset are:
Movies Table
Movie Details Table
Characters Table
Aggregating Total Box Office Earnings by Phase Using JOINs
Let's begin with our first example, where we will aggregate total box office earnings by phase. We will use an INNER JOIN on the movies and movie_details tables. We will then use the SUM function and the GROUP BY clause to find the total box office earnings per phase. This advanced query is:
There's a lot going on in this query. Let's break it down step by step.
- We first use
SELECTto obtain themovies.phasecolumn and the sum of box office sales. We use the aliasTotal Box Officefor the result of theSUM. FROM moviesselects the primary tableINNER JOIN movie_detailsspecifies the table to join withmoviesON movies.movie_id = movie_details.movie_idmatches the rows of themoviesandmovie_detailscolumn based on themovie_idGROUP BY movies.phasespecifies the rows of the output table each correspond to a phase
The output is:
The output shows the sum of box office sales for each phase.
Aggregating Average IMDb Ratings by Phase for Movies with Thor
