I am trying to calculate an average daily stock of each item in a warehouse using Ms SQL. Every incoming and outgoing quantity is recorded in the same column, let's name it [quantity]. Due to this structure the only way for me to tell the stock level for today is to simply sum all of the quantity from the beginning of time. i.e.
SELECT [item], SUM(quantity)
FROM item_table
If I want to see the stock level of yesterday I would need to following code:
SELECT [item], SUM(quantity)
FROM item_table
WHERE [date] < DATEADD(day,-1,GETDATE())
And so on for every single day. Of course I'm not going to go through the trouble of manually changing the DATEADD
number 360 times in order to get the stock level for the entire year. Hence I am using a While loop as follows:
DECLARE @intFlag INT
DECLARE @s DECIMAL = 0
DECLARE @i varchar(20) --replaced with table (see table part below)
SET @intFlag = 0
WHILE (@intFlag <= 360)
BEGIN
SET @intFlag = @intFlag + 1
SET @i = (SELECT TOP (1) [item] FROM item_table ) --replaced with table (see table part below)
SET @s = (
SELECT
SUM(quantity) + @s AS inventory
FROM item_table
WHERE
item IN (@i) --replaced with table (see table part below)
AND [Date] < dateadd(day, - @intFlag, GETDATE())
)
IF @intFlag = 360
BREAK;
END
SELECT
@i AS [item],
@s/360 AS [AVG_stock]
This is working properly so far, but I'm stuck when trying to do the same operation for multiple items.
When I try replacing the @i
parameter with a table like this:
DECLARE @items table (number varchar (20))
INSERT INTO @items
SELECT DISTINCT [Item]
FROM items_table
And try to call it in
SET @s = (
SELECT
SUM(quantity) + @s AS inventory
FROM item_table
WHERE
item IN (@items)
AND [Date] < dateadd(day, - @intFlag, GETDATE())
)
SQL cannot find the @item
table and says that it needs to be declared first. At this point I don't know why is this happening and how can I fix it. Also I have my doubts about the performance of that query since there are around 30,000 items that I would perform the stock calculation for.
Maybe there is an easy fix to this problem, or maybe someone can come up with a completely different way of calculating that damned thing. Anyway I could use any help I can get.
Kind Regards.