GROUP BY
in SQL is used to group rows that have the same values in specified columns into aggregated results. When combined with aggregate functions like COUNT()
, SUM()
, AVG()
, MAX()
, and MIN()
, it allows you to perform operations on groups of data rather than individual rows.
1. Basic Structure of GROUP BY
The typical SQL query with GROUP BY
looks like this:
sqlCopy codeSELECT column1, column2, AGGREGATE_FUNCTION(column3)
FROM table_name
GROUP BY column1, column2;
column1
andcolumn2
: These are the columns by which the results are grouped.AGGREGATE_FUNCTION
: An aggregate function likeSUM()
,AVG()
, orCOUNT()
to perform calculations on grouped data.
2. Example: Counting Items per Category
Suppose you have a table called products
:
id | category | price |
---|---|---|
1 | Books | 10 |
2 | Books | 15 |
3 | Electronics | 200 |
4 | Electronics | 300 |
To count the number of products in each category, you would use:
sqlCopy codeSELECT category, COUNT(*)
FROM products
GROUP BY category;
Output:
category | COUNT(*) |
---|---|
Books | 2 |
Electronics | 2 |
3. Using Multiple Aggregate Functions
You can use multiple aggregate functions in the same query. For example, to calculate the total price and the average price per category:
sqlCopy codeSELECT category, SUM(price) AS total_price, AVG(price) AS average_price
FROM products
GROUP BY category;
Output:
category | total_price | average_price |
---|---|---|
Books | 25 | 12.5 |
Electronics | 500 | 250.0 |
4. Filtering Groups with HAVING
Sometimes, you may want to filter the grouped results. This is done using the HAVING
clause (instead of WHERE
, which is used before aggregation). For example, to show only categories where the total price exceeds 100:
sqlCopy codeSELECT category, SUM(price) AS total_price
FROM products
GROUP BY category
HAVING SUM(price) > 100;
Output:
category | total_price |
---|---|
Electronics | 500 |
Conclusion
GROUP BY
combined with aggregate functions allows you to perform complex calculations on groups of data in SQL. It’s particularly useful for generating reports or summaries from large datasets, like counting items, calculating totals, and computing averages. You can enhance its power with multiple functions and filters using HAVING
for more refined results.
Leave a Reply