Oracle SQL:根据先前行列中的值进行选择

时间:2017-02-10 19:53:56

标签: sql database oracle

我很好奇在Oracle中根据返回行列表中的前一行编写SQL查询。基本上我必须查询我们的数据库中所有ID为2460的行,但前一行(按日期排序)的ID#为2463.有没有办法做到这一点?

很抱歉,如果这是一个令人困惑的问题,或者是一个愚蠢的问题,我是一个非常新的,并不是很擅长这些事情。我很乐意澄清任何需要澄清的事情。

谢谢!

编辑:

以下是我根据Gordon的答案运行的查询,以及我得到的结果与我想要的结果的截图。

select *
from (select activitytranledger.*, lag(reasontype) over (order by trandate) as prev_reason from activitytranledger) activitytranledger
where trandate between to_date('02/7/2017','MM/DD/YYYY')
and to_date('02/8/2017','MM/DD/YYYY')
and reasontype = 2460
and prev_reason = 2463
order by trandate
;

然后我将获取位置#并查询特定日期。

select *
from activitytranledger
where location = 5777
and trandate between to_date('02/7/2017','MM/DD/YYYY') 
and to_date('02/8/2017','MM/DD/YYYY')
order by trandate
;

使用" Transid"我可以找到第一个查询输出的特定行。但是,它似乎没有给我预期的结果。

Wanted results(请注意行的正上方行" Reasontype" 2460的原因类型为2463)

Current results(我突出显示的行应该在我指向的列中有2463)

编辑2:切换2463和2460

2 个答案:

答案 0 :(得分:2)

这是对您问题的一种解释。使用lag()和子查询:

select t.*
from (select t.*, lag(id) over (order by date) as prev_id
      from t
     ) t
where id = 2463 and prev_id = 2460;

答案 1 :(得分:0)

所以,事实证明我是个白痴。 @ GordonLinoff的解决方案非常完美我只是忘了在下面的查询中添加位置#是我想出的最终查询。我能够用我的变量替换#位置,现在可以将它插入到我的循环中,它就像魅力一样。谢谢所有贡献!

select *
from (select activitytranledger.*, lag(reasontype) over (order by trandate) as
prev_reason from activitytranledger) activitytranledger
where trandate between to_date('02/7/2017','MM/DD/YYYY')
and to_date('02/8/2017','MM/DD/YYYY')
and location = 5777
and reasontype = 2460
and prev_reason = 2463
order by trandate
;