0

我有一个查询要告诉我给活跃参与者的最新说明:

select notes.applicant_id,
   reg.program_code,
   reg.last_name,
   reg.first_name,
   reg.status_cd,
   MAX(notes.service_date) as "Last Note"
from reg inner join notes on reg.applicant_id=notes.applicant_id
where reg.status_cd='AC'
group by notes.applicant_id, reg.program_code, 
         reg.last_name, reg.first_name, reg.reg_date, 
         reg.region_code, reg.status_cd
order by MAX(notes.service_date)

但我也希望这个查询也能给出note.service_date最大值之前的结果service_date

结果看起来像这样

notes.applicant_id   reg.last_name  reg.first_name reg.status_cd  Last Note    Prior Note
 12345                 Johnson          Lori           AC        01-NOV-2011   01-OCT-2011

我在甲骨文工作。

4

2 回答 2

1

您可以使用该lag功能,或将其与同一张表连接。

这是一个更简单的例子(你还没有给我们数据样本):

create table t as
(select level as id, mod(level , 3) grp, sysdate - level dt
from dual 
connect by level < 100
)

以下是查询:

select t2.grp,t1.grp, max(t1.dt) mdt, max(t2.dt) pdt
  from t t1
  join t t2 on t1.dt < t2.dt and t1.grp = t2.grp
 group by t2.grp, t1.grp;

或者

select grp, max(pdt), max(dt)
 from(
 select grp, lag(dt) over (partition by grp order by dt) pdt, dt 
 from t)
 group by grp

是一个小提琴


在你的情况下,它可能是这样的:

select t.applicant_id, t.program_code, 
         t.last_name, t.first_name, t.reg_date, 
         t.region_code, t.status_cd,
         max(t.dt) as "Last Note",
         max(t.pdt) as "Prev Note"
from (
select notes.applicant_id,
   reg.program_code,
   reg.last_name,
   reg.first_name,
   reg.status_cd,
   notes.service_date as dt,
   lag(notes.service_date)  over (partition by notes.applicant_id,
   reg.program_code,
   reg.last_name,
   reg.first_name,
   reg.status_cd order by notes.service_date) as pdt
from reg inner join notes on reg.applicant_id=notes.applicant_id
where reg.status_cd='AC'
) t
group by t.applicant_id, t.program_code, 
         t.last_name, t.first_name, t.reg_date, 
         t.region_code, t.status_cd
order by MAX(t.dt)
于 2012-11-05T14:26:40.370 回答
0

如果我理解正确,这是一种方法:

SELECT *
  FROM (select notes.applicant_id,
               reg.program_code,
               reg.last_name,
               reg.first_name,
               reg.status_cd,
               notes.service_date AS "Last Note",
               ROW_NUMBER() OVER (PARTITION BY notes.applicant_id, reg.program_code, 
                   reg.last_name, reg.first_name, reg.reg_date, reg.region_code, 
                   reg.status_cd ORDER BY notes.service_date DESC) rn
          from reg inner join notes on reg.applicant_id=notes.applicant_id
         where reg.status_cd='AC')
 WHERE rn < 3;
于 2012-11-05T14:33:57.740 回答