Ok, I’ll do my best to explain the problem here:
The scenario is that we’re trying to keep track of currently on hand inventory for items that are continuously changing in quantity.
The way it’s set up is that any time an item changes in quantity, a row is written to a MySQL table ‘tracking’ that records the item SKU, the latest quantity, and a timestamp.
For example:
Dec. 4, 2010 --- Item #12 --- 200
Dec. 5, 2010 --- Item #33 --- 150
Dec. 8, 2010 --- Item #12 --- 50
The problem is that we want to answer the question — how many total items do we have at any point in time?
This is harder than it looks because of the sparse data problem.
Let’s say on Dec. 4, 2010, we had 200 of item #12
Then on Dec. 8, 2010, we had 50 of that same item (item #12)
Meanwhile, on Dec. 5, 2010, we had 150 of item #33
On Dec 4, 5, and 8, how many total items do we have?
The right answer is 200 total on Dec. 4, 350 on Dec. 5, and 200 on Dec. 8. How do we get those numbers? Well, we have to carry forward the quantities of items from one date to the next. Even if we don’t specify how much we have of that item on the next day, we have to assume that we had as much as we did the previous day.
So, Dec. 4, we had 200 of Item #12, and so on Dec. 5, we still have 200 of Item #12, on top of which we now have 150 of Item #33. This yields 350 on Dec. 5. Then on Dec. 8, we still have 150 of Item #33, but just 50 of Item #12, yielding just 200 items.
The query should return these results for the above data:
Dec. 4, 2010: 200 items
Dec. 5, 2010: 350 items
Dec. 8, 2010: 200 items
The tricky issue is that there might be thousands of items… this significantly complicates the MYSQL and PHP operation.
I’m looking for an optimal solution here that makes the best use of MYSQL and PHP to solve this problem. Temp tables could work as could jamming data in a big PHP associative array, but I have a feeling there’s a better way to do this.
Assuming your table is called
logand has three fields,item,ts(time stamp), andquantity, and thatquantitycontains deltas instead of totals (as recommended by Cfreak):