Money spent per customer with sub-queries

Data-Driven Decision Making in SQL

Tim Verdonck

Professor Statistics and Data Science

Subsequent SELECT statements - actresses

Query 1:

SELECT *
FROM actors
WHERE gender = 'female';
| actor_id | name          | year_of_birth | nationality | gender |
|----------|---------------|---------------|-------------|--------|
| 1        | Abbie Cornish | 1982          | Australia   | female |
| 4        | Amy Adams     | 1974          | USA         | female |
Data-Driven Decision Making in SQL

Subsequent SELECT statements - actresses

SELECT * -- Query 1
FROM actors
WHERE gender = 'female';
  • Group result table of query 1 by nationality.
  • Report year of birth for the oldest and youngest actress in each country.
SELECT af.nationality, 
       MIN(af.year_of_birth), 
       MAX(af.year_of_birth)
FROM
    (SELECT *
    FROM actors
    WHERE gender = 'female') AS af
GROUP BY af.nationality;
Data-Driven Decision Making in SQL

Result subsequent SELECT statement - actresses

SELECT af.nationality, 
       MIN(af.year_of_birth), 
       MAX(af.year_of_birth)
FROM
    (SELECT *
    FROM actors
    WHERE gender = 'female') AS af
GROUP BY af.nationality;
| nationality | min  | max  |
|-------------|------|------|
| Italy       | 1976 | 1976 |
| Iran        | 1952 | 1952 |
| USA         | 1945 | 1993 |
Data-Driven Decision Making in SQL

How much money did each customer spend?

  • First step: Add renting_price from movies to table renting.
SELECT r.customer_id,
       m.renting_price
FROM renting AS r
LEFT JOIN movies AS m
ON r.movie_id=m.movie_id;
| customer_id | renting_price |
|-------------|---------------|
| 41          | 2.59          |
| 10          | 2.79          |
| 108         | 2.39          |
| 39          | 1.59          |
| 104         | 1.69          |
Data-Driven Decision Making in SQL

How much money did each customer spend?

  • Second step:
    • group result table from first step by customer_id
    • take the sum of renting_price
SELECT rm.customer_id, 
           SUM(rm.renting_price)
FROM
       (SELECT r.customer_id, 
               m.renting_price
       FROM renting AS r
       LEFT JOIN movies AS m
       ON r.movie_id=m.movie_id) AS rm
GROUP BY rm.customer_id;
Data-Driven Decision Making in SQL

How much money did each customer spend?

| customer_id | sum   |
|-------------|-------|
| 116         | 7.47  |
| 87          | 17.53 |
| 71          | 6.87  |
| 68          | 1.59  |
| 51          | 4.87  |
Data-Driven Decision Making in SQL

Let's practice!

Data-Driven Decision Making in SQL

Preparing Video For Download...