Oracle SQL从有序数据集中获取第一个和最后一个记录

时间:2014-09-05 11:23:23

标签: sql oracle

我正在处理的软件需要获取有序数据集的第一个和最后一个记录。数据集按日期列排序。

我的数据:

--table "notes":
--    ordered by this
--                |
--                V
note_id      date_created attribute1  attribute2  ... -- I want to get
-----------------------------------------------------
596          2014/01/20   ...         ...         ... -- <- this
468          2014/02/28   ...         ...         ...
324          2014/03/01   ...         ...         ...
532          2014/04/08   ...         ...         ...
465          2014/05/31   ...         ...         ... -- <- and this

期望的输出:

596          2014/01/20   ...         ...         ...
465          2014/05/31   ...         ...         ...

3 个答案:

答案 0 :(得分:8)

您可以使用窗口功能:

select t.*
from (select t.*, row_number() over (order by date_created) as seqnum,
             count(*) over () as cnt
      from t
     ) t
where seqnum = 1 or seqnum = cnt;

在Oracle 12中,您也可以这样做:

select t.*
from t
order by date_created
fetch first 1 rows only
union all
select t.*
from t
order by date_created desc
fetch first 1 rows only;

答案 1 :(得分:4)

如果我做对了,试试这个:

select t1.*
  from YOUR_TABLE t1
     , (
        select min(note_id) keep(dense_rank first order by date_created) min_val
             , max(note_id) keep(dense_rank last order by date_created) max_val
          from YOUR_TABLE
       ) t2
 where t1.note_id = t2.min_val
    or t1.note_id = t2.max_val

答案 2 :(得分:-2)

Select * from emp where rowid  =(select min(rowid) from emp)
Union
Select * from emp where rowid  =(select max(rowid) from emp);