I have two tables which track items in different systems, for simplicity, lets call them Alpha and Beta systems. I am attempting to merge the two tables into a single table that can be correctly track the location of items.
Items tracked start in Alpha, and can move into Beta. However since the systems are not connected, the start time entered into Beta are not always matched to the end time in Alpha.
An example Item tracked correctly is as follows
System---ID----Item------- Start---------------- End
Alpha - 987 - 123 - 20/5/2015 07:00:00 - 20/5/2015 08:00:00
Alpha - 374 - 123 - 20/5/2015 08:00:00 - 20/5/2015 09:00:00
Beta - 184 - 123 - 20/5/2015 09:00:00 - 20/5/2015 10:00:00
Beta - 798 - 123 - 20/5/2015 10:00:00 - 20/5/2015 12:00:00
My issue is because the systems are not linked, I have cases where items appear in both Alpha and Beta at the same time. As follows
System---ID----Item------- Start---------------- End
Alpha - 987 - 123 - 20/5/2015 07:00:00 - 20/5/2015 08:00:00
Beta - 184 - 123 - 20/5/2015 07:30:00 - 20/5/2015 10:00:00
Alpha - 374 - 123 - 20/5/2015 08:00:00 - 20/5/2015 09:00:00
Beta - 798 - 123 - 20/5/2015 10:00:00 - 20/5/2015 12:00:00
Alpha is the better system, and should always be trusted.
So my desired outcome in the above situation would be to modify record 184 and change it's start time to the end time of record 374.
There is an another case also which should be accounted for, and that's where an Alpha record begins and ends before the last Beta record starts.
Make sense? I hope so, it's been driving me nuts for the last few days.
Thank you for any help you can give.
If you use SQL Server 2012 and later (thanks for the tip Karl) you can use LAG and LEAD, as shown here:
SQL Fiddle
Query 1:
Results: