The GROUP BY
statement in SQL Server is used to group rows that have the same values in specified columns into summary rows. It is often used in combination with aggregate functions such as COUNT
, SUM
, AVG
, MAX
, and MIN
to perform calculations on each group of rows.
Here's the basic syntax of the GROUP BY
statement:
Consider a table called Sales
with the following structure:
To find the total sales amount for each year, you can use the GROUP BY
statement as follows:
The result of the above query will look like this:
You can group by multiple columns to get more detailed summaries. For example, to find the total sales amount for each product in each year:
The result will look like this:
The HAVING
clause is used to filter groups based on a condition. It is similar to the WHERE
clause but is used with aggregate functions.
The result will show only products with total sales greater than 1500:
The GROUP BY
statement is powerful for generating summarized reports and analyzing data across different dimensions. If you have specific scenarios or need further examples, feel free to let me know!