2017-02-10 114 views
1

我很想知道如何在Oracle中基于返回行列表中的上一行编写SQL查询。基本上,我必须查询我们的数据库中所有ID为2460的行,但前一行(按日期排序)的ID号是2463.有没有办法做到这一点?Oracle SQL:根据先前行中的值进行选择列

对不起,如果这是混乱或一个愚蠢的问题,我是非常新的,并不是很擅长这类事情。我很乐意澄清任何需要澄清的事情。

谢谢!

编辑:

下面是我根据戈登与我越来越VS我想要的结果,结果的截图沿着答案运行查询。

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(注意行直接与2460“Reasontype”行上面有着怎样的理由类型2463)

Current results(我强调该行应该有2463的,我指着列)

编辑2:切换2463和2460

+1

编辑您的问题,并提供样本数据和预期结果。 –

回答

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

@AdamNeighbors - 进一步解释,如果你可以直接在'where'子句中使用'lag()...'不幸的是,你不能。子查询是不可避免的。但是,在您的公式中,您并不是从表格中进行选择,而是从“返回行列表”中进行选择。在建立这个列表的地方,你可能会在那里添加'lag'函数,并且去掉一层嵌套的子查询。 (但你是否可以做到这一点取决于查询的作用。) – mathguy

+0

@GordonLinoff我已经做了一些编辑,使其更清晰一些。 –

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 
;