The 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.
The 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)
FROM table
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)
FROM sales_data
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)
FROM sales_data
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
| OBJECT_ID | PRICE | TYPE |
|---|---|---|
| 1 | 200 | LOW |
| 2 | 500 | MEDIUM |
| 3 | 900 | HIGH |
| 4 | 500 | MEDIUM |
SELECT type, SUM(price)
FROM store
GROUP BY type;
| TYPE | PRICE |
|---|---|
| LOW | 200 |
| MEDIUM | 1000 |
| HIGH | 900 |