In this chapter, we will learn about the *GROUP BY* and *HAVING* clauses in SQL. These
clauses allow us to group data and perform aggregations, as well as filter the results based
on those aggregations.
---
*GROUP BY Clause*
The *GROUP BY* clause is used to group rows that have the same values in specified
columns into summary rows, often used with aggregate functions (like *SUM()*, *AVG()*,
*COUNT()*, etc.). This enables us to perform aggregations on each group of data rather
than on individual rows.
Example: Grouping Sales Data by Salesperson
Suppose we have a table of *sales_data*, and we want to calculate the total sales for each
salesperson. We can use the *SUM()* function along with the *GROUP BY* clause to
achieve this:
```sql
SELECT salesperson, SUM(sales) AS total_sales
FROM sales_data
GROUP BY salesperson;
```
*Result:*
| salesperson | total_sales |
|-------------|-------------|
| John | 5000 |
| Jane | 7000 |
| Bob | 3000 |
Here, the data is grouped by *salesperson*, and the *SUM()* function calculates the total
sales for each salesperson.
---
*HAVING Clause*
The *HAVING* clause is used to filter groups based on the result of an aggregation. It is
similar to the *WHERE* clause, but while *WHERE* filters rows before aggregation,
*HAVING* filters groups after the aggregation.
Example: Filtering Salespeople with Total Sales Greater Than 4000