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.

Similar Reads

What is the PARTITION BY Clause?

The PARTITION BY clause is a type of clause that is used with window functions to divide the result set into partitions on which the function is applied. It allows us to perform calculations and aggregations within each partition independently....

What is GROUP BY Clause?

The GROUP BY clause is used to aggregate data based on one or more columns and group rows with identical values into summary rows. It is widely used via aggregate functions like SUM, COUNT, and AVG to perform calculations on each group....

Examples of PARTITION BY and GROUP BY

To understand PARTITION BY vs GROUP BY in SQL we need a table on which we will perform various operations and queries. Here we will consider a table called sales which contains product_id, category and sales_amount as Columns....

Examples of GROUP BY Clause

Example 1: Total Sales Amount by Category...

Examples of PARTITION BY Clause

Example 1: Rank of Products within Each Category...

Difference Between PARTITION BY and GROUP BY

Let’s compare PARTITION BY and GROUP BY in a tabular format....

Conclusion

Overall, Understanding the differences between PARTITION BY and GROUP BY is important for effective data analysis and aggregation in SQL. While GROUP BY is used for summarizing data into groups, PARTITION BY allows for more advanced calculations within each partition. We have saw various examples of PARTITION BY and GROUP BY to get the better understanding of them....