The GROUP BYclause in
SQL Server is used to group rows that have the same values in specified columns into aggregatedata, such as sums, averages, counts, etc. Here is a step-by-step guide on how to use the
GROUP BY clause:
Basic Syntax
SELECT column1, column2, AGGREGATE_FUNCTION(column3)
FROM table_name
GROUP BY column1, column2;
Aggregate Functions
Common aggregate functions include:
SUM()
COUNT()
AVG()
MIN()
MAX()
Example Use Cases
1. Sum of Sales by Salesperson
Assume we have a table Sales with the following columns: SaleID,
SaleAmount, SalesPersonID, and SaleDate.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
The
GROUP BYclause in SQL Server is used to group rows that have the same values in specified columns into aggregate data, such as sums, averages, counts, etc. Here is a step-by-step guide on how to use theGROUP BYclause:Basic Syntax
Aggregate Functions
Common aggregate functions include:
SUM()COUNT()AVG()MIN()MAX()Example Use Cases
1. Sum of Sales by Salesperson
Assume we have a table
Saleswith the following columns:SaleID,SaleAmount,SalesPersonID, andSaleDate.To calculate the total sales amount for each salesperson:
Output:
2. Count of Sales by Salesperson
To count the number of sales made by each salesperson:
Output:
3. Average Sale Amount by Salesperson
To calculate the average sale amount for each salesperson:
Output:
Using GROUP BY with Multiple Columns
You can group by multiple columns to get more granular aggregates.
Output:
Filtering Groups with HAVING
The
HAVINGclause is used to filter groups based on aggregate functions.Example: Total Sales Greater than 300
Output:
Complete Example
Combining everything together, here is a full example including table creation, data insertion, and querying with
GROUP BYandHAVING:Read more
Write a query to retrieve the total number of employees in each department.
How do I use CTE to simplify complex queries in SQL Server?
Difference between INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN in SQL Server.