August 13, 2024

Srikaanth

Find the Average Order Value by Customer SQL Server

Find the Average Order Value by Customer Query Using MS SQL Server?


To find the average order value by customer, you need to:

  1. Calculate the total value of each order.
  2. Aggregate these order values by customer.
  3. Calculate the average order value for each customer.

Assuming you have the following tables:

  • OrderDetails:
    • OrderID
    • ProductID
    • Quantity
    • UnitPrice
  • Orders:
    • OrderID
    • CustomerID
    • OrderDate

Here’s a SQL query to calculate the average order value by customer:

SQL Query

WITH OrderValues AS (
    SELECT
        o.CustomerID,
        o.OrderID,
        SUM(od.Quantity * od.UnitPrice) AS OrderValue
    FROM Orders o
    JOIN OrderDetails od ON o.OrderID = od.OrderID
    GROUP BY o.CustomerID, o.OrderID
),
AverageOrderValues AS (
    SELECT
        CustomerID,
        AVG(OrderValue) AS AverageOrderValue
    FROM OrderValues
    GROUP BY CustomerID
)
SELECT
    c.CustomerID,
    c.CustomerName,
    a.AverageOrderValue
FROM AverageOrderValues a
JOIN Customers c ON a.CustomerID = c.CustomerID
ORDER BY c.CustomerID;

Explanation:

  1. CTE OrderValues:

    • SUM(od.Quantity * od.UnitPrice) AS OrderValue: Calculates the total value of each order.
    • GROUP BY o.CustomerID, o.OrderID: Groups by CustomerID and OrderID to compute the order value for each order.
  2. CTE AverageOrderValues:

    • AVG(OrderValue) AS AverageOrderValue: Calculates the average order value for each customer.
    • GROUP BY CustomerID: Groups by CustomerID to aggregate the average order value for each customer.
  3. Final Query:

    • JOIN Customers c ON a.CustomerID = c.CustomerID: Joins with the Customers table to get customer names.
    • ORDER BY c.CustomerID: Orders the results by CustomerID.

Example Data and Results

Assume the OrderDetails and Orders tables have the following data:

OrderDetails Table:

OrderIDProductIDQuantityUnitPrice
1110100
22550
313100
411100
52250

Orders Table:

OrderIDCustomerIDOrderDate
110012024-01-01
210012024-01-05
310022024-01-10
410022024-01-15
510032024-01-20

Customers Table:

CustomerIDCustomerName
1001Alice
1002Bob
1003Charlie

Using the query, the result might be:

CustomerIDCustomerNameAverageOrderValue
1001Alice700
1002Bob400
1003Charlie100

This result shows the average value of orders placed by each customer.

You can execute this query in SQL Server Management Studio or any SQL query tool connected to your SQL Server to get the average order value by customer. Adjust the table and column names according to your actual database schema.


https://mytecbooks.blogspot.com/2024/08/find-average-order-value-by-customer.html
Subscribe to get more Posts :