GROUP BY clause in SQL Server is used in conjunction with aggregate functions (such as SUM, COUNT, AVG, etc.) to group the results of a
SELECT statement by one or more columns.
GROUP BY clause is used to divide the rows in a table into smaller groups that have the same values in the specified column(s). The
aggregate functions are then applied to each group, rather than to the entire table.
GROUP BY syntax
SELECT column_name1, aggregate_function(column_name2)
GROUP BY column_name1
GROUP BY example
For example, if you have a table of sales data and you want to see the total sales by category, you could use the following query:
SELECT category, SUM(sales)
GROUP BY category;
This query would return a result set that shows the total sales for each category in the sales_data table. The
GROUP BY clause groups the data by the category column, and the
SUM function calculates the total sales for each group.
It is important to note that when using the
GROUP BY clause, all non-aggregated columns in the
SELECT statement must be included in the
GROUP BY clause.
SELECT category, product, SUM(sales)
GROUP BY category, product;
This query would return a result set that shows the total sales for each category and product in the sales_data table.
Example of store table
SELECT type, SUM(price)
GROUP BY type;