Understanding SQL GROUP BY Clause
Introduction to GROUP BY Clause
The SQL GROUP BY clause is used to group rows that have the same values in specified columns into summary rows.
Using GROUP BY
Let's consider a sample table called "Sales" to understand how GROUP BY works:
Product | Category | Amount |
---|---|---|
Product A | Electronics | 1000 |
Product B | Clothing | 500 |
Product C | Electronics | 800 |
Product D | Books | 300 |
Using GROUP BY with Aggregate Functions
You can combine GROUP BY with aggregate functions like SUM, AVG, COUNT, etc., to calculate summaries of grouped data:
SELECT Category, SUM(Amount) AS TotalSales
FROM Sales
GROUP BY Category;
Output:
Category | TotalSales |
---|---|
Electronics | 1800 |
Clothing | 500 |
Books | 300 |
Using GROUP BY with HAVING Clause
The HAVING clause is used to filter results after grouping. It's similar to the WHERE clause but operates on grouped data:
SELECT Category, AVG(Amount) AS AvgAmount
FROM Sales
GROUP BY Category
HAVING AVG(Amount) > 750;
Output:
Category | AvgAmount |
---|---|
Electronics | 900 |
Comments
Post a Comment