2015-06-21 79 views
0

列表中的最新的記錄,我有以下表中選擇在甲骨文基於最新活動記錄

enter image description here

我將向尊貴其基礎上突出顯示的記錄喜歡的一個數據,例如:當我選擇基於Foreign_key柱以及所述第二記錄記錄是「CONTENT =反應或PROCESS_ID = 11」然後我需要將其作爲標籤「PROCESS」。如果第二記錄不是內容=響應而是「CONTENT =啓動或PROCESS_ID = 20」(Foreign_key = 101)那麼我想它貼上標籤「不處理」

提示:此表中的活動是在處理日期訂單(ASC)中創建的。

任何人都可以建議我SQL查詢,請記住我需要執行查詢CASE由於其他JOIN語句的負載。

回答

-1

Analytic functions是你的救援

這裏一個完整的示例:

drop table test; 
create table test 
(id number, 
content varchar2(30), 
processdate date, 
process_id number, 
foreighn_key number); 

insert into test values(1,'New',to_date('18.06.2015 10','dd.mm.yyyy hh24'), 10,100); 
insert into test values(2,'Response',to_date('18.06.2015 11','dd.mm.yyyy hh24'), 11,100); 
insert into test values(3,'Reply',to_date('18.06.2015 12','dd.mm.yyyy hh24'), 12,100); 
insert into test values(4,'Closed',to_date('18.06.2015 13','dd.mm.yyyy hh24'), 13,100); 
insert into test values(5,'New',to_date('18.06.2015 14','dd.mm.yyyy hh24'), 10,101); 
insert into test values(6,'Initiate',to_date('18.06.2015 15','dd.mm.yyyy hh24'), 20,101); 
insert into test values(7,'Target',to_date('18.06.2015 16','dd.mm.yyyy hh24'), 21,101); 
insert into test values(8,'Closed',to_date('18.06.2015 17','dd.mm.yyyy hh24'), 13,101); 
commit; 

with trans as (
select ID, CONTENT, PROCESSDATE, PROCESS_ID, FOREIGHN_KEY, 
-- first row per FK gets rn = 1 
row_number() over (partition by FOREIGHN_KEY order by PROCESSDATE) rn, 
-- lookup the next row value of the column 
lead(CONTENT) over (partition by FOREIGHN_KEY order by PROCESSDATE) content_lead, 
lead(PROCESS_ID) over (partition by FOREIGHN_KEY order by PROCESSDATE) Process_id_lead 
from test order by processdate) 
select 
ID, CONTENT, PROCESSDATE, PROCESS_ID, FOREIGHN_KEY, 
case when content_lead = 'Response' OR Process_id_lead = 11 then 'PROCESS' 
when content_lead = 'Initiate' OR Process_id_lead = 20 then 'NOT PROCESS' end as trans_type 
from trans 
where rn = 1 

ID CONTENT      PROCESSDATE   PROCESS_ID FOREIGHN_KEY TRANS_TYPE 
---------- ------------------------------ ------------------- ---------- ------------ ----------- 
    1 New       18.06.2015 10:00:00   10   100 PROCESS  
    5 New       18.06.2015 14:00:00   10   101 NOT PROCESS