根据记录列表中的日期,活动选择Oracle中的最新记录

时间:2015-06-21 12:37:42

标签: sql oracle subquery case .when

我在其中一个表格中有以下数据

enter image description here

我想根据突出显示的记录区分它们,例如:当我选择基于 Foreign_key 列的记录时,第二条记录是“Content = Response OR Process_id = 11” 然后我需要将其标记为“PROCESS”。如果第二条记录不是 Content = Response ,而是“Content = Initiate OR Process_id = 20”(Foreign_key = 101),那么我想标记它“NOT PROCESS“即可。

提示:此表中的活动是在 Processdate 订单(ASC)中创建的。

任何人都可以建议我使用SQL查询,请记住,由于其他JOIN语句的加载,我需要在 CASE 中执行查询。

1 个答案:

答案 0 :(得分:-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