T-SQL Tutorial

SQL Server GROUP BY


SQL Server GROUP BY is a powerful clause used in SQL queries to group data based on one or more columns. It allows you to group records in a table based on common values and perform aggregate functions on those groups, such as calculating the sum, average, or count of records in each group.


Syntax

The syntax for using GROUP BY in SQL Server is as follows:

SELECT column1, column2, ..., aggregate_function(column_name)
FROM table_name
WHERE condition
GROUP BY column1, column2, ...;

In this syntax, "column1, column2, ..." refers to the columns that you want to group by. These columns can be either numeric or non-numeric data types.

The aggregate function (such as SUM, COUNT, AVG, MIN, MAX) is applied to a column to perform calculations on the grouped data.

The WHERE clause can be used to filter the records before grouping them.


Example

Here's an example of using GROUP BY in SQL Server:
Suppose we have a table named "Orders" with columns "OrderID", "CustomerID", "OrderDate", and "TotalAmount". We want to group the orders by customer and calculate the total amount of orders for each customer. We can write the following SQL query:

SELECT CustomerID, SUM(TotalAmount) AS TotalOrderAmount
FROM Orders
GROUP BY CustomerID;

This query will group all the orders by customer ID and calculate the sum of the total amount of each customer's orders. The result will be a table with two columns: "CustomerID" and "TotalOrderAmount".

In conclusion, SQL Server GROUP BY is a useful clause for grouping data and performing aggregate functions on those groups. It is an essential tool for data analysis and reporting in SQL Server.