I would like to ask for your help for constructing a single ORACLE SQL statement:
using job table as below
Object | Operation | Time
A | Move | 12:01
B | Move | 12:02
C | Pickup | 12:03
D | Move | 12:04
B | Pickup | 12:05
to get the result table as below.
Object | Operation | Time | Cause
A | Move | 12:01 | C
B | Move | 12:02 | C
D | Move | 12:04 | B
This is to figure out which Pickup operation caused each Move operation.
“Cause” column must include Object of the pickup job record with smallest time right next to move operation.
I have some ideas as below but do not know how to.
-. It requires join statement between subquery for Move and subquery for Pickup
-. Subquery for Pickup must be partitioned by move record to be joined
-. Must select top record only from each partition of Pickup subquery
This is my try:
see SQLFiddle
I’ve put column time as number, this does not have any importance as it is sortable.
I’ve splitted the table in two, Moves and Pickups and the join is made on time, time of
pickupbeing greater than time ofmove. (This type of join is not great on performance). Then Ichoosethe pickup with smallesttime(firstclause, withorder by p.time).