Find Products with Sales Above the Average Sales of All Products

Find Products with Sales Above the Average Sales of All Products Query Using MS SQL Server?


To find products with sales above the average sales of all products, you need to follow these steps:

  1. Calculate the total sales for each product.
  2. Compute the average sales across all products.
  3. Filter products that have sales above this average.

Assuming you have the following tables:

  • OrderDetails:
    • OrderID
    • ProductID
    • Quantity
    • UnitPrice (price per unit of the product)

Here’s how you can write the SQL query:

SQL Query


WITH ProductSales AS (
    SELECT
        ProductID,
        SUM(Quantity * UnitPrice) AS TotalSales
    FROM OrderDetails
    GROUP BY ProductID
),
AverageSales AS (
    SELECT
        AVG(TotalSales) AS AvgSales
    FROM ProductSales
)
SELECT
    ps.ProductID,
    ps.TotalSales
FROM ProductSales ps
JOIN AverageSales asales
    ON ps.TotalSales > asales.AvgSales;

Explanation:

  1. CTE ProductSales:

    • SUM(Quantity * UnitPrice) AS TotalSales: Calculates the total sales amount for each product by multiplying quantity by unit price and summing it up.
    • GROUP BY ProductID: Groups the results by product to get the total sales for each product.
  2. CTE AverageSales:

    • AVG(TotalSales) AS AvgSales: Computes the average sales amount across all products from the ProductSales CTE.
  3. Final Query:

    • JOIN AverageSales asales ON ps.TotalSales > asales.AvgSales: Filters products whose total sales exceed the average sales amount.

Example Data and Results

Assume the OrderDetails table has the following data:

OrderIDProductIDQuantityUnitPrice
1A10100
2B5200
3A3100
4C8150
5B7200

The ProductSales CTE would produce:

ProductIDTotalSales
A1300
B2400
C1200

The AverageSales CTE would calculate:

AvgSales
1633.33

The final query result would be:

ProductIDTotalSales
B2400

In this case, Product B has total sales above the average sales amount.

You can execute this query in SQL Server Management Studio or any SQL query tool connected to your SQL Server to find products with sales above the average sales of all products.


Post a Comment

Previous Post Next Post