开发者

Issue in SQL query full scanning twice?

开发者 https://www.devze.com 2023-03-06 22:23 出处:网络
Table A IDEmpNo开发者_开发百科Grade -------------------- 1100HIGH 2105LOW 3100MEDIUM 4100LOW 5105LOW Query:

Table A

ID    EmpNo   开发者_开发百科Grade
--------------------    
1      100    HIGH
2      105    LOW
3      100    MEDIUM
4      100    LOW
5      105    LOW

Query:

select * 
from A 
where EMPNO = 100 
  and rownum <= 2 
order by ID desc 

I tried this query to retrieve max and max-1 value; I need to compare the grade from max and max-1, if equals I need to set the flag as 'Y' or 'N' without using a cursor. Also I don't want to scan the entire record twice.

Please help me.


ROWNUM is applied before ORDER BY, so you need to nest the query like this:

select * from
(select * from A where EMPNO =100 order by ID desc)
where rownum<=2

That only performs one table scan (or it may use an index on EMPNO).


select *
from (
select id, emp_no, grade
       , case 
          when lag(grade) over (order by emp_no desc) = grade 
          then 'Y' 
          else 'N'     
          end
          as flag
      , dense_rank() over( order by emp_no desc)  as rank
from t
)
where rank <=2
;
0

精彩评论

暂无评论...
验证码 换一张
取 消