Sql Oracle:使用子查询中的复合键选择

Sql Oracle:使用子查询中的复合键选择,sql,oracle,subquery,Sql,Oracle,Subquery,现在的情况是这样的——我们的记录使用名称/日期的复合键。我希望看到在一行中执行了2个特定操作的所有名称,因此我希望执行以下操作 select name from (select name as n, date as d from table where action='action1'), (select name from table where name = n and date > d and action='action2' and rownum=1 order by da

现在的情况是这样的——我们的记录使用名称/日期的复合键。我希望看到在一行中执行了2个特定操作的所有名称,因此我希望执行以下操作

 select name from 
 (select name as n, date as d from table where action='action1'),
 (select name from table where name = n and date > d and action='action2' and rownum=1 order by date desc)
但它将n和d算作无效标识符。我怎样才能让它做我需要的

一种方法可能是:

SELECT
  a1.name
FROM
  (SELECT name, date FROM table WHERE action = 'action1') a1
JOIN
  (SELECT name, date FROM table WHERE action = 'action2') a2
  ON
  a2.name = a1.name
  AND
  a2.date > a1.date
如果单个名称的每个操作可以有多个实例,则可能会出现重复的实例。在这种情况下,使用
选择DISTINCT
消除DUP就足够了


请注意,这并不意味着这两个动作一个接一个地发生,只是动作2发生在动作1之后的某个时间。

分析功能非常适合这种情况。。。。免责声明这是快速和肮脏的和列名有点误导。滞后/超前是您想要使用的选项


他想采取行动。他不希望action1.5介于action1和action2之间。@GiorgiNakeuri是的,我看到了,但从他的实际查询只要求一个接一个的事实来看,我认为他可能不是字面上的“一排”。这就是为什么我指出我的回答不能保证没有干预行动。是的,我只想直接采取下一个行动,没有干预行动。然而,加入可能是个好主意。感谢您可以修改上面的查询,在不存在的地方添加一个
子查询,以验证action1和action2之间没有其他操作。当然还有其他方法,例如使用分析函数。
select name,thedate,theaction,prev_action,prev_date from 
 (
 select name,thedate,theaction,
 lag(theaction) over (partition by name order by thedate,theaction) as prev_action,
lag(thedate) over (partition by name order by thedate,theaction) as prev_date
from table1 
order by name,thedate,theaction
)
where theaction = 'action1' and prev_action = 'action2'
;