Calculate the Percentage of Total Sales for Each Product SQL Server

Calculate the Percentage of Total Sales for Each Product Query Using MS SQL Server?


To calculate the percentage of total sales for each product in SQL Server, you need to perform the following steps:

  1. Calculate the total sales amount for each product.
  2. Calculate the total sales amount across all products.
  3. Compute the percentage of total sales for each product based on the total sales.

Assuming you have a table named Sales with the following columns:

  • ProductID
  • Amount (the sales amount for each transaction)

Here's a step-by-step SQL query to achieve this:

SQL Query

WITH TotalSales AS (
    SELECT
        ProductID,
        SUM(Amount) AS ProductTotal
    FROM Sales
    GROUP BY ProductID
),
OverallTotal AS (
    SELECT
        SUM(ProductTotal) AS TotalAmount
    FROM TotalSales
)
SELECT
    t.ProductID,
    t.ProductTotal,
    (t.ProductTotal / o.TotalAmount * 100) AS PercentageOfTotalSales
FROM TotalSales t
CROSS JOIN OverallTotal o
ORDER BY t.ProductID;

Explanation:

  1. CTE TotalSales:

    • Calculates the total sales amount for each product.
    • SUM(Amount) AS ProductTotal: Sums up the sales amounts grouped by ProductID.
  2. CTE OverallTotal:

    • Computes the total sales amount across all products.
    • SUM(ProductTotal) AS TotalAmount: Sums up the product totals from the TotalSales CTE.
  3. Final Query:

    • CROSS JOIN OverallTotal o: Joins each product’s total with the overall total to calculate the percentage.
    • (t.ProductTotal / o.TotalAmount * 100) AS PercentageOfTotalSales: Computes the percentage of total sales for each product.

Example Data and Results

Assume the Sales table has the following data:

ProductIDAmount
1100
1150
2200
250
3300

The TotalSales CTE will produce:

ProductIDProductTotal
1250
2250
3300

The OverallTotal CTE will produce:

TotalAmount
800

The final query result will be:

ProductIDProductTotalPercentageOfTotalSales
125031.25
225031.25
330037.50

This result shows the percentage of total sales contributed by each product.

You can execute this query in SQL Server Management Studio or any SQL query tool connected to your SQL Server to get the percentage of total sales for each product.


Post a Comment

Previous Post Next Post