Oracle自我加入

时间:2014-06-18 08:24:15

标签: oracle oracle10g

我的表中有三列ID,开始日期,结束日期。我只需要获取“ID”的记录,其中没有记录大于相同ID的结束日期。样本数据

ID START_DATE END_DATE
----------------------

 1    01-APR-2013              31-MAR-2014 
 1    01-APR-2014              31-MAR-2015 
 2    01-APR-2013              31-MAR-2014 
 3    01-JUN-2013              31-MAY-2014

查询应仅生成

  

2 01-APR-2013 31-MAR-2014
  3 01-JUN-2013 31-MAY-2014

我试过了。

 With Query_Table As (
         Select '1' ID ,To_date('01-APR-2013','DD-MON-YYYY') from_date,To_date('31-MAR-2014','DD-MON-YYYY') end_date From Dual 
         Union
         Select '1' ID ,To_date('01-APR-2014','DD-MON-YYYY') from_date,To_date('31-MAR-2015','DD-MON-YYYY') end_date From Dual 
         Union
         Select '2' ID,To_date('01-APR-2013','DD-MON-YYYY') from_date,To_date('31-MAR-2014','DD-MON-YYYY') end_date From Dual 
         Union
         Select '3' Id,To_Date('01-JUN-2013','DD-MON-YYYY') From_Date,To_Date('31-JUL-2014','DD-MON-YYYY') End_Date From Dual )
         ,Query_Table2 as (
         Select '1' ID ,To_date('01-APR-2013','DD-MON-YYYY') from_date,To_date('31-MAR-2014','DD-MON-YYYY') end_date From Dual 
         Union
         Select '1' ID ,To_date('01-APR-2014','DD-MON-YYYY') from_date,To_date('31-MAR-2015','DD-MON-YYYY') end_date From Dual 
         Union
         Select '2' ID,To_date('01-APR-2013','DD-MON-YYYY') from_date,To_date('31-MAR-2014','DD-MON-YYYY') end_date From Dual 
         Union
         Select '3' Id,To_Date('01-JUN-2013','DD-MON-YYYY') from_date,To_Date('31-JUL-2014','DD-MON-YYYY') end_date From Dual )
         Select Id,From_Date,End_Date
         From Query_Table2
         where Query_Table2.id not in (select id from Query_Table where Query_Table2.from_date>Query_Table.end_Date )

1 个答案:

答案 0 :(得分:0)

我是在简化这个吗?或者这简单如下?

SELECT mst.id, mst.start_date, mst.end_date
  FROM table_x mst
 WHERE (mst.start_date, mst.id) = (SELECT MAX (sub.start_date), MAX (sub.id)
                             FROM table_x sub
                            WHERE sub.start_date = mst.start_date)