简体   繁体   中英

Comparing current row and next row in oracle sql

I need to compare current row and next row and based on some comparison need to derive a column value. Currently approach I'm following is making two different record sets and then use rank function and then by joining rank functions I m able to achieve this. However, this seems to be tedious approach, is there a better way to achieve this. I m currently writing query something like below:

select 
< comparing columns from two record sets and deriving column value> 
              (
        select(<some complex logic>, rank from a) rcdset, 
    (select <some complex logic>, rank +1 from a) rcdset2 where rcdset.rnk = rcdset1.rnk (+)

And this query the current row needs to be compared with every other row in the table except the previous ones, how can I do this?

Your question is quite vague, but you can simply use lead() :

select a.*,
       lead(col) over (order by <ordering col>) as next_col_value
from a;

You can incorporate case logic for a comparison.

Recursive subquery factoring clause aka CTE or WITH clause often can help in such cases, because oracle optimizer can decide to "materialize" your subquery and it allows to reduce extra io and calculations.

For example:

with hard_view as (
select ... 
from ...
)
select *
from hard_view v1,
     hard_view v2
where v1.rnk = v2.rnk+1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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