4 IM Aggregation and Grouping
4 IM Aggregation and Grouping
Objectives:
Learn how to perform aggregation function on data
Understand GROUP BY and HAVING clauses
Lab Activities:
1. Writing queries to calculate SUM, AVG, COUNT, etc.
2. Using GROUP BY to group data based on the specific columns.
3. Applying HAVING clause to filter grouped data.
1. Open SQL Server Management Studio (SSMS): Launch SSMS and connect to your SQL Server
instance.
2. Select a Database: In the Object Explorer, expand the server node, then expand the Databases
node, and choose the database you want to work with by right-clicking and selecting "New
Query" or by selecting it from the "Available Databases" dropdown in the query window.
3. Write the SQL Query: In the query window, you can start writing your SQL query. Here are
some examples for common aggregate functions:
a. SUM:
To calculate the sum of a column, you can use the SUM() function:
Replace column_name with the name of the column you want to sum, and table_name with the
name of the table.
b. AVG:
To calculate the average of a column, you can use the AVG() function:
c. COUNT:
To count the number of rows in a table, you can use the COUNT() function:
SELECT COUNT(*) AS row_count
FROM table_name;
To count the number of non-null values in a specific column:
4. Execute the Query: After writing your query, you can execute it by clicking the "Execute" button
(or press F5). The results will be displayed in the "Results" pane.
5. View the Results: The result set will display the calculated value(s) based on your query.
6. (Optional) Save the Query: You can save the query for future use by clicking "File" -> "Save" or
using the shortcut Ctrl + S.
Remember to replace column_name and table_name with your actual column and table names.
SQL Server Management Studio provides an intuitive interface for writing and executing SQL
queries, making it easy to work with aggregate functions and retrieve the desired results.
Sample Output:
Sample Output:
Sample Output:
Sample Output:
Sample Output:
Sample Output:
Exercise 4.1g: Calculate the Total Quantity Sold for a Specific Product
Calculate the total quantity sold for a specific product (replace <ProductID> with the actual product ID).
Sample Output:
Sample Output:
Using the GROUP BY clause in SQL Server Management Studio (SSMS) allows you to group data
based on specific columns and perform aggregate functions on those groups. Here are the steps to use
GROUP BY:
Let's say you have a table named "Orders" with columns "CustomerID," "ProductID," and "Quantity."
You want to find the total quantity of products purchased by each customer. You can write the following
SQL query:
SELECT CustomerID, SUM(Quantity) AS TotalQuantityPurchased
FROM Orders
GROUP BY CustomerID;
In this query:
SELECT ProductID,
SUM(OrderQty) AS TotalQuantitySold,
SUM(LineTotal) AS TotalSalesAmount
FROM Sales.SalesOrderDetail
GROUP BY ProductID;
SELECT CustomerID,
COUNT(*) AS NumberOfOrders
FROM Sales.SalesOrderHeader
GROUP BY CustomerID;
SELECT DepartmentID,
AVG(Salary) AS AverageSalary
FROM HumanResources.Employee
GROUP BY DepartmentID;
SELECT CategoryID,
AVG(ListPrice) AS AverageListPrice
FROM Production.Product
GROUP BY CategoryID;
SELECT TerritoryID,
SUM(TotalDue) AS TotalSalesAmount
FROM Sales.SalesOrderHeader
GROUP BY TerritoryID;
SELECT Status,
COUNT(*) AS NumberOfOrders
FROM Sales.SalesOrderHeader
GROUP BY Status;
Problem 10: Group Sales by Year and Calculate Total Sales Amount
Group sales data from the "Sales.SalesOrderHeader" table by year. Calculate the total sales amount
for each year.
Problem 12: Group Orders by Ship Date and Calculate Total Orders
Group order data from the "Sales.SalesOrderHeader" table by ship date. Calculate the total number of
orders shipped on each date.
Using the HAVING clause in SQL Server Management Studio (SSMS) allows you to filter the results of
a GROUP BY query based on aggregate conditions. It is typically used to filter groups of rows produced
by the GROUP BY clause. Here are the steps to apply the HAVING clause:
Replace column1, column2, etc. with the columns you want to group by.
Replace aggregate_function(column) with the aggregate function (e.g., SUM(column),
AVG(column), COUNT(column)) you want to apply to the grouped data.
Replace table with the name of the table you are querying.
Replace condition with the condition you want to apply to the aggregated results.
Let's say you have a table named "Orders" with columns "CustomerID" and "TotalAmount." You want to
find customers who have placed orders with a total amount greater than $1,000. You can write the
following SQL query:
In this query:
The result will display the "CustomerID" and the corresponding total order amount for customers who
meet the condition specified in the HAVING clause.
Using the HAVING clause is essential when you need to filter grouped data based on aggregate
conditions, allowing you to extract meaningful insights from your data in SQL Server.
These exercises will help you practice using the HAVING clause to filter grouped data in SQL Server.