2015-09-10 52 views
-2

表結構狀態:(數據庫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 

問題:如何獲得客戶的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

+0

你期望的輸出似乎不隨輸入表JIVE。你能澄清這一點嗎? –

+0

是的,我認爲第二排應該像'27-02-2015 | PQR'? – Crazy2crack

+0

@Bhushan ...你確定2015年2月27日的狀態應該是ABC而不是PQR?如果我根據你的預期產出正確解釋,那麼2015年8月4日的狀態應該是PQR。 – Codeek

回答

2

您可以使用前導分析函數來獲取間隔結束。然後在兩者之間進行搜索。

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 
+0

感謝您的答案(和+1) – Bhushan

2

使用新引進的行限制子句中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; 
+0

感謝您的答案(和+1) – Bhushan

1

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; 
+0

@ lad2025謝謝,我修復它以匹配OP更新。現在計算的狀態匹配慾望輸出狀態。 –

+0

感謝您的答案(和+1) – Bhushan