Sums and Averages
COUNT counts; SUM adds up. SUM(column) adds up the values of a column in all the rows found, and AVG(column) gives their average: the sum divided by how many values there are. If you bought one copy of every game in the shop, you'd pay:
SELECT SUM(price) AS all_games,
AVG(price) AS average_price
FROM games;| all_games | average_price |
|---|---|
| 570 | 28.5 |
Remember from lesson 4 that 7 / 2 is 3, because both numbers are whole? AVG doesn't do that: it always gives a decimal number, even when all the values are whole. And an average often has many decimal places, so you'll usually round it with ROUND. This is the average price in order_items, as it is and rounded:
SELECT AVG(price) AS average_paid,
ROUND(AVG(price), 2) AS rounded
FROM order_items;| average_paid | rounded |
|---|---|
| 28.3333333333333 | 28.33 |
In the parentheses, you can write any expression, not just a column. The database works it out for each row and then adds up the results. That's how you work out what orders are worth. In order_items, each row has the number of copies and the price of one copy, so a row is worth quantity * price. These are the items of the orders 5 and 6:
SELECT order_id, game_id, quantity, price,
quantity * price AS item_total
FROM order_items
WHERE order_id IN (5, 6);| order_id | game_id | quantity | price | item_total |
|---|---|---|---|---|
| 5 | 4 | 1 | 30 | 30 |
| 5 | 20 | 1 | 35 | 35 |
| 6 | 2 | 2 | 15 | 30 |
And this adds up their item_total:
SELECT SUM(quantity * price) AS total
FROM order_items
WHERE order_id IN (5, 6);| total |
|---|
| 95 |
A sum over the whole table order_items is the value of everything that customers have ordered. That's not quite what the shop has earned: it includes the items of the two refunded orders, for which the customers got their money back. Whether an order was refunded is written in another table, orders, and you'll learn to combine tables in the next lesson. Until then, the sums in this lesson include the refunded orders, except in the last exercise, where you'll leave them out another way.
Like COUNT(column), SUM and AVG skip NULL, so AVG divides by the number of values, not of rows. And when there's nothing to add up, because WHERE found no row, they give NULL, not 0. If you need a 0 there, use COALESCE(SUM(price), 0) from lesson 4.
Typical mistake: SUM(price) instead of SUM(quantity * price). In order 6, the customer bought two copies of Pixel Racer, and SUM(price) would count only one of them.
Instructions
How many copies of games have customers ordered? Add up the column quantity of order_items, in a column copies_ordered:
| copies_ordered |
|---|
| 45 |
Below it, compute the value of all the items ordered: the sum of quantity * price, in a column items_value:
| items_value |
|---|
| 1260 |
And show the average price of the games for all ages (age_rating 3), rounded to 2 decimal places, in a column average_price:
| average_price |
|---|
| 25.71 |
Start programming for free
3/10