The GROUP BY clause in SQL is used to arrange identical data into groups. It allows you to perform aggregate functions (like COUNT, SUM, AVG, etc.) on each group of data. Here's how it works:
- Grouping: It consolidates rows that have the same values in specified columns into a single row for each unique value.
- Aggregation: After grouping, you can apply aggregate functions to summarize data within each group.
For example, if you have a sales table and you want to find the total sales for each product category, you would use GROUP BY to group the results by category and then sum the sales amounts.
Example:
SELECT category, SUM(sales) as total_sales
FROM sales_data
GROUP BY category;
This query will return the total sales for each product category in the sales_data table.
