August 13, 2024

Srikaanth

Get the Total Sales for Each Product by Month SQL Server

Get the Total Sales for Each Product by Month Query Using MS SQL Server?


To get the total sales for each product by month, you need to aggregate sales data on a monthly basis for each product. This typically involves:

  1. Extracting the month and year from the order date.
  2. Grouping the sales data by product and month.
  3. Summing the sales amounts for each product in each month.

Assuming you have the following tables:

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

Here’s a SQL query to get the total sales for each product by month:

SQL Query


WITH MonthlySales AS (
    SELECT
        od.ProductID,
        DATEPART(YEAR, o.OrderDate) AS SalesYear,
        DATEPART(MONTH, o.OrderDate) AS SalesMonth,
        SUM(od.Quantity * od.UnitPrice) AS TotalSales
    FROM OrderDetails od
    JOIN Orders o ON od.OrderID = o.OrderID
    GROUP BY
        od.ProductID,
        DATEPART(YEAR, o.OrderDate),
        DATEPART(MONTH, o.OrderDate)
)
SELECT
    p.ProductID,
    p.ProductName,
    ms.SalesYear,
    ms.SalesMonth,
    ms.TotalSales
FROM MonthlySales ms
JOIN Products p ON ms.ProductID = p.ProductID
ORDER BY p.ProductID, ms.SalesYear, ms.SalesMonth;

Explanation:

  1. CTE MonthlySales:

    • DATEPART(YEAR, o.OrderDate) AS SalesYear: Extracts the year from the OrderDate.
    • DATEPART(MONTH, o.OrderDate) AS SalesMonth: Extracts the month from the OrderDate.
    • SUM(od.Quantity * od.UnitPrice) AS TotalSales: Calculates the total sales amount for each product in each month.
    • GROUP BY od.ProductID, DATEPART(YEAR, o.OrderDate), DATEPART(MONTH, o.OrderDate): Groups by ProductID, year, and month to aggregate sales.
  2. Final Query:

    • JOIN Products p ON ms.ProductID = p.ProductID: Joins with the Products table to get product names.
    • ORDER BY p.ProductID, ms.SalesYear, ms.SalesMonth: Orders the results by product and then by year and month.

Example Data and Results

Assume the OrderDetails and Orders tables have the following data:

OrderDetails Table:

OrderIDProductIDQuantityUnitPrice
1110100
215100
3220200
4115100
5210200

Orders Table:

OrderIDOrderDate
12024-01-10
22024-01-15
32024-02-05
42024-02-10
52024-03-01

Products Table:

ProductIDProductName
1Widget A
2Widget B

The query would produce:

ProductIDProductNameSalesYearSalesMonthTotalSales
1Widget A202411500
1Widget A202421500
2Widget B202424000
2Widget B202432000

This result shows the total sales for each product, broken down by month.

You can execute this query in SQL Server Management Studio or any SQL query tool connected to your SQL Server to get the total sales for each product by month. Adjust the table and column names according to your actual database schema.


https://mytecbooks.blogspot.com/2024/08/get-total-sales-for-each-product-by.html
Subscribe to get more Posts :