Group By with Having
Previously, we have learnt to perform aggregations on all the rows of a table. Now, we shall look at how to split a table into multiple groups and apply aggregation on each group.
The GROUP BY keyword in SQL is used to group rows which have the same values for the mentioned attributes. You can perform aggregations on these groups to get finer analytics.
HAVING keyword is used to further refine the data by filtering the aggregated values. Let’s explore more about GROUP BY and HAVING clauses with the following database.
Database
The database consists of
- Schema
GROUP BY
The
Syntax
Example
Get the total score of each player in the database.
Output
name | total_score |
---|---|
David | 105 |
Joseph | 116 |
Lokesh | 186 |
... | ... |
Try it Yourself!
- Get the maximum score of each player.
- Get the total number of sixes hit by each player.
GROUP BY with WHERE
We use WHERE clause to filter the data before performing aggregation.
Syntax
Example
Get the number of half-centuries scored by each player
Output
name | half_centuries |
---|---|
David | 1 |
Joseph | 2 |
Lokesh | 3 |
... | ... |
Try it Yourself!
- Get year wise number of half-centuries scored by each player.
HAVING
Syntax
Example
Get the
Output
name | half_centuries |
---|---|
Lokesh | 2 |
Ram | 3 |
Try it Yourself!
- Get the name and number of half-centuries scored by each player who scored at least a half-century in two matches.