6

我想请您帮忙构建一条 ORACLE SQL 语句:

使用工作表如下

Object | Operation | Time  
A      | Move      | 12:01  
B      | Move      | 12:02  
C      | Pickup    | 12:03  
D      | Move      | 12:04  
B      | Pickup    | 12:05  

得到如下结果表。

Object | Operation | Time  | Cause  
A      | Move      | 12:01 | C  
B      | Move      | 12:02 | C  
D      | Move      | 12:04 | B 

这是为了弄清楚哪个 Pickup 操作导致了每个 Move 操作。
“原因”列必须包含移动操作旁边时间最短的取件作业记录的对象。

我有以下一些想法,但不知道如何去做。
-。它需要在 Move 的子查询和 Pickup 的子查询之间使用 join 语句
。Pickup 的子查询必须按要加入的移动记录进行分区
-。只能从 Pickup 子查询的每个分区中选择顶部记录

4

3 回答 3

4

这是我的尝试:

select  m.object, m.operation, m.time, 
  max(p.object) keep (dense_rank first order by p.time) cause,
  max(p.time) keep (dense_rank first order by p.time) cause_time
from a m
join a p on (p.time > m.time)
where m.operation = 'Move'
and p.operation = 'Pickup'
group by m.object, m.operation, m.time;

SQLFiddle

我已将列时间作为数字,这没有任何重要性,因为它是可排序的。

我已将表格分成两部分,移动和拾取,并且按时进行连接,时间pickup大于move. (这种类型的连接在性能上不是很好)。然后我choose用最小的timefirst子句,with order by p.time)来取货。

于 2012-12-18T06:38:53.513 回答
4

这是我的尝试:

select object, operation, time, t.pobject
from a join 
   (select object pobject, time cur, lag(time,1, 0) over (order by time  ) prev 
      from a
     where operation = 'Pickup')t 
on a.time > t.prev and a.time <= t.cur
where operation = 'Move';

这是一个sqlfiddle

于 2012-12-18T07:16:24.757 回答
4

有一个来自old school

select j1.Object, j1.Operation, j1.Time, substr(min(j2.Time || j2.Object), 6) Cause
from job j1, job j2
where j1.Operation like 'Move'
  and j1.Time < j2.Time
  and j2.Operation like 'Pickup'
group by j1.Object, j1.Operation, j1.Time

这是SQLFiddle

于 2012-12-18T08:54:58.093 回答