Find the Products that Have Been Ordered in Every Month of the Current Year

Find the Products that Have Been Ordered in Every Month of the Current Year Query Using MS SQL Server?


To find products that have been ordered in every month of the current year using MS SQL Server, you typically need to have at least two tables:

  1. Orders: Contains order details including order dates.
  2. OrderDetails: Contains information about the products in each order.

Here’s a general approach using these tables:

Example Table Structures


-- Orders table
CREATE TABLE Orders (
    OrderID INT PRIMARY KEY,
    OrderDate DATE NOT NULL
);

-- OrderDetails table
CREATE TABLE OrderDetails (
    OrderDetailID INT PRIMARY KEY,
    OrderID INT FOREIGN KEY REFERENCES Orders(OrderID),
    ProductID INT,
    Quantity INT
);

Query to Find Products Ordered in Every Month of the Current Year

-- CTE to get the distinct months in which each product was ordered
WITH MonthlyOrders AS (
    SELECT
        od.ProductID,
        YEAR(o.OrderDate) AS OrderYear,
        MONTH(o.OrderDate) AS OrderMonth
    FROM
        OrderDetails od
    JOIN Orders o ON od.OrderID = o.OrderID
    WHERE
        YEAR(o.OrderDate) = YEAR(GETDATE()) -- Current year
    GROUP BY
        od.ProductID,
        YEAR(o.OrderDate),
        MONTH(o.OrderDate)
),

-- CTE to get the number of unique months per product
ProductMonthCount AS (
    SELECT
        ProductID,
        COUNT(DISTINCT OrderMonth) AS OrderedMonths
    FROM
        MonthlyOrders
    GROUP BY
        ProductID
)

-- Select products that have been ordered in all 12 months
SELECT
    pmc.ProductID
FROM
    ProductMonthCount pmc
WHERE
    pmc.OrderedMonths = 12;

Explanation

  1. CTE MonthlyOrders: This common table expression retrieves the distinct months each product has been ordered in the current year. It joins the OrderDetails with Orders to get the order date and then extracts the year and month from the order date.

  2. CTE ProductMonthCount: This calculates the number of unique months in which each product has been ordered by counting distinct months.

  3. Final Selection: The main query selects products from ProductMonthCount that have been ordered in all 12 months of the current year (OrderedMonths = 12).

This approach assumes that:

  • Each order's date is correctly recorded.
  • The product can be uniquely identified by ProductID.
  • You want to include products that have been ordered in every month from January to December of the current year.

Adjust the table and column names as needed to fit your actual database schema.


Post a Comment

Previous Post Next Post