获取特定日期的状态

get status on specific date

Table结构:(数据库为oracle 12c

CUSTOMER_ID | STATUS | STATUS_FROM_DATE
        101 | ABC    | 10-01-2015
        101 | PQR    | 27-02-2015
        101 | LMN    | 04-08-2015
        101 | ABC    | 08-09-2015

问题: 如何从上面 table 获取特定日期的 status 客户?

例如:

CUSTOMER_ID | Input Date | Expected Output
        101 | 15-01-2015 | ABC
        101 | 27-02-2015 | PQR
        101 | 28-02-2015 | PQR
        101 | 10-09-2015 | ABC

在上面的例子中,
ABC 是客户在 15-01-2015 的状态,因为这是在 10-01-2015 设置的,直到 27-02-2015 才更改。
PQR 是客户在 28-02-2015 的状态,因为这是在 27-02-2015 设置的,直到 04-08-2015.

才更改

您可以使用引导解析函数来获取间隔的结束。然后使用 between.

搜索
select * from 
(

    select 
      customer_id, 
      status, 
      status_from_date, 
      nvl(lead(status_from_date) over (partition by customer_id order by status_from_date)-1,
          to_date('2099','yyyy')
         )as end_date
    from your_table

)
where your_date_here between status_start_date and end_date

Oracle 12c

中使用新引入的行限制子句
select <your input date> as date_, expected_status
from myt
where status_date <= <your input date>
order by status_date desc
fetch first 1 rows only;

SQL FIDDLE DEMO

 with ranges as (
     select t.*, 
     lead(STATUS_FROM_DATE,1, (select sysdate from dual)) 
       over (partition by CUSTOMER_ID order by STATUS_FROM_DATE) as status_change
     from Table1 t
 )
 select r.status, s."Date", s."Expected Output"
 from ranges r
 inner join TestStatus s
    on s."Date" < r.status_change
  and  s."Date" >= r.STATUS_FROM_DATE;