Aggregate Functions
In the article about grouping, we discussed that when using the GROUP BY operator, we can use aggregate functions. Let's talk more about them π³.
General structure of a query with an aggregate function
MySQL 8.4
SELECT { literal | aggregate_function | grouping_field } [, ...]
FROM table_name
GROUP BY grouping_field [, ...];- [ ]optional part
- { a | b }one of the options
- ...can be repeated
- literal
A fixed value such as 'text' or 1. It is the same for every group.
- aggregate_function
A function that computes one value from all rows of a group, for example AVG(price).
- grouping_field
The column that splits rows into groups: rows with the same value end up in one group. You can list several columns separated by commas.
- table_name
- The table whose rows are grouped.
For example, a query using the AVG aggregate function might look like this:
MySQL 8.4SELECT home_type, AVG(price) as avg_price FROM Rooms GROUP BY home_type
Description of aggregate functions
Examples
-
Find the number of each type of home and sort the resulting list in descending order:
MySQL 8.4SELECT home_type, COUNT(*) as amount FROM Rooms GROUP BY home_type ORDER BY amount DESC -
For each room, find the latest end date of reservations (the end_date field)
MySQL 8.4SELECT room_id, MAX(end_date) AS last_end_date FROM Reservations GROUP BY room_id