Grouping Part 1
Part of the Fundamentals section of Coddy's SQL journey — lesson 36 of 72.
We have calculated data for the entire field thus far, and now we will introduce the ability to calculate data for specific groups.
workers
| id | area | age |
|---|---|---|
| 1 | A | 35 |
| 2 | A | 37 |
| 3 | B | 29 |
| 4 | B | 39 |
If we write
SELECT AVG(age) as avg_age FROM workersWe will receive only the average age of all the workers together.
What if we want to calculate the average age for each area?
For that, we can use the GROUP BY keywords
SELECT area, AVG(age) as avg_age FROM workers
GROUP BY areaThe result:
| area | avg_age |
|---|---|
| A | 36 |
| B | 34 |
Now we know that the average age in Area A is 36 and the average age in Area B is 34.
Challenge
EasyAvailable tables and columns:
<b>foods</b>:<b>name</b>,<b>type</b>,<b>pH</b>
Calculate, for each food type, the average pH value.
Name the columns: type, ph_average.
Use ROUND(value, 2) to round the average to two decimal places.
Cheat sheet
Use GROUP BY to calculate aggregate functions for specific groups:
SELECT area, AVG(age) as avg_age FROM workers
GROUP BY areaThis groups rows by the area column and calculates the average age for each group separately.
Use ROUND(value, decimal) to round numerical results to a specified number of decimal places:
SELECT ROUND(AVG(age), 2) FROM workersTry it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4More Keywords
The IN keywordThe BETWEEN keywordThe LIKE keywordThe AS keywordRecap - Cellphone Models2Conditions
Conditions BasicsThe AND keywordThe OR keywordThe NOT keywordMultiple Conditions CombinedParenthesisBooleans5Arithmetic Operations
Mathematical OperatorsMathematical ColumnsThe Modulo OperationThe ROUND() Function3Specific Return Format
Null valuesSort Results Part 1Sort Results Part 2Recap - Cyber Security FirmLimit number of recordsRecap - Vehicle Factory6Intro Challenges
Recap - Parliamentary ElectionRecap - Police Criminal ArrestRecap - Bar Beverage ContainerRecap - Engineer new columns