Examples of GROUP BY Clause
Example 1: Total Sales Amount by Category
Query:
SELECT category, SUM(sales_amount) AS total_sales
FROM sales
GROUP BY category;
Output
Explanation: In the above query, We uses GROUP BY
to group rows by category and SUM
()
to calculate the total sales amount for each category in the sales table.
Example 2: Average Sales Amount by Category
Query:
SELECT category, AVG(sales_amount) AS avg_sales
FROM sales
GROUP BY category;
Output:
Explanation: In the above query, We uses GROUP BY
to group rows by category and AVG
()
to calculate the average sales amount for each category in the sales table.
PARTITION BY vs GROUP BY in SQL
In SQL both PARTITION BY and GROUP BY are important clauses used for data aggregation and analysis. Sometimes they work as same but they serve different purposes and are applied in different situations. In this article, we’ll understand both of them along with the syntax, multiple examples for both clauses and also the differences between them.