Get the Average Order Value for Each Product Category Query Using MS SQL Server?
To get the average order value for each product category using Microsoft SQL Server, you need to join the relevant tables, aggregate the order values by category, and then compute the average.
Assuming you have the following tables:
Orderstable with columnsOrderIDandOrderAmount.OrderItemstable with columnsOrderID,ProductID, andQuantity.Productstable with columnsProductID,CategoryID, andProductName.Categoriestable with columnsCategoryIDandCategoryName.
Here’s a step-by-step SQL query to achieve this:
SQL Query
-- Query to get the average order value for each product category
WITH OrderDetails AS (
SELECT
o.OrderID,
SUM(oi.Quantity * p.Price) AS OrderValue
FROM
Orders o
JOIN OrderItems oi ON o.OrderID = oi.OrderID
JOIN Products p ON oi.ProductID = p.ProductID
GROUP BY
o.OrderID
),
CategoryOrderValues AS (
SELECT
p.CategoryID,
AVG(od.OrderValue) AS AverageOrderValue
FROM
OrderDetails od
JOIN Products p ON od.ProductID = p.ProductID
GROUP BY
p.CategoryID
)
SELECT
c.CategoryID,
c.CategoryName,
cov.AverageOrderValue
FROM
CategoryOrderValues cov
JOIN Categories c ON cov.CategoryID = c.CategoryID
ORDER BY
cov.AverageOrderValue DESC;
Explanation
OrderDetailsCTE:- Calculates the total value of each order by joining the
Orders,OrderItems, andProductstables. SUM(oi.Quantity * p.Price) AS OrderValue: Computes the total value for each order based on the quantity of each product and its price.GROUP BY o.OrderID: Groups byOrderIDto get the total order value for each order.
- Calculates the total value of each order by joining the
CategoryOrderValuesCTE:- Computes the average order value for each product category.
AVG(od.OrderValue) AS AverageOrderValue: Calculates the average order value by category.GROUP BY p.CategoryID: Groups byCategoryIDto get the average order value for each category.
Main Query:
JOIN Categories c ON cov.CategoryID = c.CategoryID: Joins with theCategoriestable to get category names.ORDER BY cov.AverageOrderValue DESC: Orders the results by average order value in descending order.
Additional Considerations
- Price Column: Ensure the
Productstable has aPricecolumn. If the price is stored differently or in another table, adjust the query accordingly. - Missing Data: Ensure there are no missing or incorrect price or quantity values that could affect the calculations.
- Performance: Indexes on
OrderID,ProductID, andCategoryIDcan help improve query performance.
Adjust the column names and table structure based on your actual schema. This query provides a clear method for calculating and retrieving the average order value for each product category.

Post a Comment