I have a database that tracks the location of inventory.
The application was poorly written and is a mess of spaghetti code with no MVC separation and updates to the model can happen in any number of files.
When the application was first written it only needed to track the location the inventory currently resides in so a SiteID column exists in the inventory table that lists it’s currently assigned to.
Since then the owner has decided he wants to maintain a history of which locations the inventory is assigned to. Rather than trawl through all the code to try and find all the places it possibly updates I added a trigger ON UPDATEand ON INSERT to the inventory table that records movements in a history table.
The initial requirement was to be able to view the movement history of a piece of inventory which is easily solved with SELECT * FROM history WHERE InvID = X ORDER BY timestamp DESC
Now I’ve been asked to produce a list for a given location that shows when a piece of inventory is assigned to the site, and the date it leaves (example below). Ideally I’d like to achieve this without modifying the existing schema and triggers if possible.
I’m able to retrieve a list of all the inventory that was assigned to the site at one point and the date which it was assigned. What I’m struggling with is how to find the date that piece of inventory left the site. I could do it within the application but I wondered if it’s possible with SQL.
Inventory table
InventoryID InventoryName SiteID
=========== ============= ======
1 Widget A $ID
2 Widget B $ID
3 Widget C $ID
Locations table
SiteID SiteName
====== ========
1 Somewhere
2 Nowhere
3 Anywhere
History table
InvID SiteID Timestamp
===== ====== =========
1 1 2012-01-01
1 2 2012-01-02
2 1 2012-01-03
1 1 2012-01-04
New view should look something like this
InvID DateIn DateOut
===== ========== ==========
1 2012-01-01 2012-01-02
2 2012-01-03 NULL
1 2012-01-04 NULL
Psuedo code to produce table with a programming language (post-processing SQL query
SELECT * FROM history WHERE SiteID = 1
foreach (row in result) {
DateOut = SELECT * FROM history WHERE InvID = result.InvID AND timestamp > result.timestamp LIMIT 1
}
try this:
Its just possible with left outer join to the same table and take the min date from the right table
Sql Fiddle demo