简体   繁体   English

在子查询之间的ORACLE join语句中选择最高记录

[英]selecting top record in ORACLE join statement between subqueries

I would like to ask for your help for constructing a single ORACLE SQL statement: 我想请求您帮助构建单个ORACLE SQL语句:

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. 这是为了确定哪个Pickup操作导致每个Move操作。
"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 它需要在Move的子查询和Pickup的子查询之间使用join语句
-. - 。 Subquery for Pickup must be partitioned by move record to be joined 必须通过要连接的移动记录对分拣的子查询进行分区
-. - 。 Must select top record only from each partition of Pickup subquery 必须仅从Pickup子查询的每个分区中选择最高记录

This is my try: 这是我的尝试:

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;

see SQLFiddle 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 pickup being greater than time of move . 我把表分成了两个,Moves和Pickups,并且按时进行连接, pickup时间大于move时间。 (This type of join is not great on performance). (这种类型的连接在性能上并不是很好)。 Then I choose the pickup with smallest time ( first clause, with order by p.time ). 然后我choose time的拾音器( first子句, order by p.time )。

This is my try: 这是我的尝试:

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';

Here is a sqlfiddle 这是一个sqlfiddle

There is one from 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

Here is SQLFiddle 这是SQLFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM