假设我有这样的oracle表。
EMP_ID DATE_EX ATTN LEV REV
-------- ----------- ---- ---- ----
50001000 13-07-2017 22 02 1
50001000 19-08-2017 26 04 2
50001001 30-06-2017 20 05 3
50001000 17-09-2017 20 05 4
50001000 19-08-2017 25 05 5
50001001 27-07-2017 21 04 6
50001000 17-09-2017 26 02 7
50001000 13-07-2017 21 04 8
我想获得最后更新的单行,其最大DATE_EX和最大REV。
我的预期输出是
EMP_ID DATE_EX ATTN LEV REV
-------- ----------- ---- ---- ----
50001000 17-09-2017 26 02 7
我正在寻找一个有效的SQL查询。请帮忙.. 查询必须兼容oracle 10g
答案 0 :(得分:0)
规范方法是:
select t.*
from (select t.*
from t
order by t.date_ex desc, t.rev desc
) t
where rownum = 1;
如果您关心效果,则需要(date_ex desc, rev desc)
上的索引。
答案 1 :(得分:0)
最有效的查询 - 特别是它不需要子查询 - 使用FIRST / LAST聚合函数,如下所示。当最大DATE_EX没有“关联”时(DATE_EX的关系最大REV),这种方法效果最佳。
with
test_data ( emp_id, date_ex, attn, lev, rev ) as (
select 50001000, to_date('13-07-2017', 'dd-mm-yyyy'), 22, '02', 1 from dual union all
select 50001000, to_date('19-08-2017', 'dd-mm-yyyy'), 26, '04', 2 from dual union all
select 50001001, to_date('30-06-2017', 'dd-mm-yyyy'), 20, '05', 3 from dual union all
select 50001000, to_date('17-09-2017', 'dd-mm-yyyy'), 20, '05', 4 from dual union all
select 50001000, to_date('19-08-2017', 'dd-mm-yyyy'), 25, '05', 5 from dual union all
select 50001001, to_date('27-07-2017', 'dd-mm-yyyy'), 21, '04', 6 from dual union all
select 50001000, to_date('17-09-2017', 'dd-mm-yyyy'), 26, '02', 7 from dual union all
select 50001000, to_date('13-07-2017', 'dd-mm-yyyy'), 21, '04', 8 from dual
)
-- End of simulated inputs (for testing purposes only, not part of the solution).
-- SQL query begins BELOW THIS LINE.
select max(emp_id) keep (dense_rank last order by date_ex, rev) as emp_id,
max(date_ex) as date_ex,
max(attn) keep (dense_rank last order by date_ex, rev) as attn,
max(lev) keep (dense_rank last order by date_ex, rev) as lev,
max(rev) keep (dense_rank last order by date_ex) as rev
from test_data
;
EMP_ID DATE_EX ATTN LEV REV
-------- ---------- ---- --- ---
50001000 17-09-2017 26 02 7
答案 2 :(得分:0)
如果您使用的是Oracle 12.1或更高版本,那么它只是:
select * from yourtable
order by date_ex desc, rev desc
fetch first row only;