sqlplus选择合并日期之间的记录

时间:2014-12-09 06:15:13

标签: sqlplus

  

表名:document_archive_doc_perms

表格说明:

 - location char(1),  document_id  number(5),  permission_id number(5),
   permission_type char(1), date_time_from date,  date_time_to date,
   ecode number(5), ecode_s number(2),  approved_by number(5),
   approved_by_ecode number(2), approved_on date, primary
   key(location,document_id,permission_id));

我的疑问:

select permission_id,document_id,date_time_from,date_time_to,approved_on,permission_type from document_archive_doc_perms 
where document_id=3 and ecode=1695 and approved_on is not null and (sysdate between date_time_from and date_time_to);

我的输出是

PERMISSION_ID DOCUMENT_ID DATE_TIME DATE_TIME APPROVED_ P
------------- ----------- --------- --------- --------- -
            5           3 01-DEC-14 31-DEC-14 08-DEC-14 V
            7           3 09-DEC-14 31-DEC-14 09-DEC-14 P

这里我需要的是记录的最新许可(即最大权限为permit_id) 怎么做。?

1 个答案:

答案 0 :(得分:0)

您可以使用分析rank()来电:

SELECT permission_id, 
       document_id, 
       date_time_from, 
       date_time_to, 
       approved_on, 
       permission_type
FROM   (SELECT permission_id, 
               document_id, 
               date_time_from, 
               date_time_to, 
               approved_on, 
               permission_type,
               RANK() OVER (ORDER BY perission_id ASC) AS rk
        FROM   document_archive_doc_perms 
        WHERE  document_id = 3 AND 
               ecode = 1695 AND 
               approved_on IS NOT NULL AND 
               SYSDATE BETWEEN date_time_from AND date_time_to
       )
WHERE  rk = 1