比较来自相同主值的两个日期范围

时间:2018-01-12 08:40:16

标签: oracle-sqldeveloper

我有一个apartment_id两个日期范围,他们代表租用公寓的不同租房者如下:

Apt_id  Date_of_MovingIn  Date_of_Movingout
123456       01.01.2015         30.06.2015
123456       01.07.2015            Null

Null意味着公寓仍然租用。我想把数据称为:

 Apt_id  Date_of_MovingIn  Date_of_Movingout
123456      01.01.2015           Null

显示第一个开始日期,直到最后一个或空。请指教,谢谢!

1 个答案:

答案 0 :(得分:0)

这是一个丑陋的选择:

SQL> with test (apt_id, date_of_moving_in, date_of_moving_out)
  2       as (select 123456, date '2015-01-01', date '2015-06-30' from dual
  3           union
  4           select 123456, date '2015-07-01', null from dual
  5           union
  6           select 444, date '2017-12-20', date '2017-12-25' from dual)
  7    select apt_id,
  8           min (date_of_moving_in),
  9           (select date_of_moving_out
 10              from test t1
 11             where     t1.apt_id = t.apt_id
 12                   and t1.date_of_moving_in = (select max (t2.date_of_moving_in)
 13                                                 from test t2
 14                                                where t2.apt_id = t1.apt_id))
 15              date_of_moving_out
 16      from test t
 17  group by apt_id;

    APT_ID MIN(DATE_O DATE_OF_MO
---------- ---------- ----------
    123456 01.01.2015
       444 20.12.2017 25.12.2017

SQL>

另一个更漂亮的人:

SQL> with test (apt_id, date_of_moving_in, date_of_moving_out)
  2       as (select 123456, date '2015-01-01', date '2015-06-30' from dual
  3           union
  4           select 123456, date '2015-07-01', null from dual
  5           union
  6           select 444, date '2017-12-20', date '2017-12-25' from dual),
  7       sorter
  8       as (select apt_id,
  9                  date_of_moving_in,
 10                  date_of_moving_out,
 11                  rank ()
 12                     over (partition by apt_id order by date_of_moving_in asc)
 13                     rnk_min,
 14                  rank ()
 15                     over (partition by apt_id order by date_of_moving_in desc)
 16                     rnk_max
 17             from test)
 18    select s1.apt_id, s1.date_of_moving_in, s2.date_of_moving_out
 19      from sorter s1, sorter s2
 20     where s1.apt_id = s2.apt_id and s1.rnk_min = 1 and s2.rnk_max = 1
 21  order by s1.apt_id desc;

    APT_ID DATE_OF_MO DATE_OF_MO
---------- ---------- ----------
    123456 01.01.2015
       444 20.12.2017 25.12.2017

SQL>