Get the Highest and Lowest Sale Amount for Each Product Query Using MS SQL Server?
To retrieve the highest and lowest sale amount for each product using Microsoft SQL Server, you need to:
- Aggregate sale amounts for each product to determine the highest and lowest sale amount.
- Group by product to calculate these values.
Assuming you have the following tables:
OrderItemstable with columns:OrderID,ProductID,Quantity,UnitPrice.Salestable with columns:OrderID,SaleAmount(this might be redundant ifSaleAmountis computed fromQuantityandUnitPrice).
Here's how you can write a query to find the highest and lowest sale amount for each product:
SQL Query
-- Find the highest and lowest sale amount for each product
WITH SaleAmounts AS (
SELECT
oi.ProductID,
oi.UnitPrice * oi.Quantity AS SaleAmount
FROM
OrderItems oi
),
ProductSales AS (
SELECT
sa.ProductID,
MAX(sa.SaleAmount) AS MaxSaleAmount,
MIN(sa.SaleAmount) AS MinSaleAmount
FROM
SaleAmounts sa
GROUP BY
sa.ProductID
)
SELECT
p.ProductID,
p.ProductName, -- Assuming you have a Products table with ProductName
ps.MaxSaleAmount,
ps.MinSaleAmount
FROM
ProductSales ps
JOIN Products p ON ps.ProductID = p.ProductID
ORDER BY
p.ProductID;
Explanation
SaleAmountsCTE:oi.UnitPrice * oi.Quantity AS SaleAmount: Calculates the sale amount for each item in an order.- This assumes that
SaleAmountis not directly stored but needs to be calculated asUnitPrice * Quantity.
ProductSalesCTE:MAX(sa.SaleAmount) AS MaxSaleAmount: Finds the maximum sale amount for each product.MIN(sa.SaleAmount) AS MinSaleAmount: Finds the minimum sale amount for each product.GROUP BY sa.ProductID: Groups byProductIDto compute the highest and lowest sale amounts for each product.
Main Query:
JOIN Products p ON ps.ProductID = p.ProductID: Joins with theProductstable to get additional details likeProductName.ORDER BY p.ProductID: Orders the results byProductIDfor better readability.
Additional Considerations
- Data Accuracy: Ensure that the
OrderItemstable accurately reflects all sales and thatUnitPriceandQuantityare correctly populated. - Handling Missing Data: If some products have no sales, they won't appear in the results. Handle such cases if necessary.
- Indexes: Indexes on
ProductID,UnitPrice, andQuantitycan help improve query performance.
Adjust column names and table structures based on your actual schema. This query will effectively provide the highest and lowest sale amount for each product.

Post a Comment