Group By clause in SQL

The GROUP BY statement in SQL is used to arrange identical data into groups. This statement is often used with aggregate functions (like COUNT, SUM, MAX, MIN, AVG) to perform an operation on each group of identical data.
Basic Concept
When you use GROUP BY, you specify one or more columns that you want to group by, and SQL aggregates the results for each group defined by the unique combinations of values in the specified columns.
Syntax
The basic syntax for GROUP BY is:
SELECT column_name(s), AGGREGATE_FUNCTION(column_name)
FROM table_name
WHERE condition
GROUP BY column_name(s);
Example
Suppose you have a database with a table called Sales that records sales transactions. The table structure includes Product, SalesDate, and Amount columns.
Here’s how you might use GROUP BY to find the total sales for each product:
SELECT Product, SUM(Amount) as TotalSales
FROM Sales
GROUP BY Product;
This query does the following:
SELECT: Identifies the columns to be returned. Here, it returns the
Productand the sum of theAmountcolumn.FROM: Specifies the table from which to retrieve the data.
GROUP BY: Groups the rows that have the same value in the
Productcolumn into summary rows.
More Complex Example
Let's add complexity by including a condition and another grouping level. Assume you also want to group the sales data by year in addition to the product:
SELECT Product, EXTRACT(YEAR FROM SalesDate) as Year, SUM(Amount) as TotalSales
FROM Sales
WHERE SalesDate >= '2020-01-01'
GROUP BY Product, EXTRACT(YEAR FROM SalesDate);
This query groups sales by both product and year (extracted from SalesDate), and:
WHERE: Filters the records to include only those where
SalesDateis on or after January 1, 2020.EXTRACT: A function used to get a specific part of a date value, here extracting the year from
SalesDate.GROUP BY: Now groups by both
Productand the year extracted fromSalesDate.
These examples explain how GROUP BY can be used to summarize data, making it a powerful tool for data analysis in SQL.


