The oracle table that I'm trying to query has multiple date columns that give timestamps for warehouse activity, both with an item and location associated with them.
I'm trying to find the item that was in a location at a certain date. Activity timestamps of actions in that location (such as adding more product, switching with a new product, counting, etc) have the item listed. I'm looking up the max value of a date given that it's below a certain target, in order to find the item that was last recorded there within the time of the timestamp and my target date. my query for this is as follows:
SELECT ITEM,LOCATION,ANVDATE
FROM PLATEHISTORY WHERE
ANVDATE = (SELECT MAX(ANVDATE) FROM PLATEHISTORY WHERE
ANVDATE <= ('3-Jan-18') AND LOCATION in ('4446D01'))
AND LOCATION in ('4446D01');
This is all fine and good, but that second column WHENOCCURRED also has timestamps that I want, and they don't match up. A newer activity with a different item might have occurred in WHENOCCURRED, but not shown up in ANVDATE, in which case I would be getting false information about the item in the location if I query ANVDATE.
here's a brief illustration of what I mean:
LOCATION ITEM ANVDATE WHENOCCURRED
4446D01 MK0C2AM/A 02-JAN-18 06-FEB-18
4446D01 MP812LL/A 14-DEC-17 31-DEC-17
4446D01 MP812LL/A 14-DEC-17 18-DEC-17
4446D01 MP812LL/A 14-DEC-17 26-DEC-17
4446D01 MK0C2AM/A 02-JAN-18 08-JAN-18
As you can see, I'm looking to get Item "MK0C2AM/A", but It has to be returned via a date before 3-Jan-18, so trying to do a CASE comparison between ANVDATE and WHENOCCURRED for the greater one would chuck out the entry that actually has the item I want.
How do I check both ANVDATE and WHENOCCURRED for the latest update before a target time, choose only the closest one, and get the ITEM and LOCATION from it?