我有一个查询,我会告诉我活跃参与者的最新说明:
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
我在oracle工作。
答案 0 :(得分: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
Here是一个小提琴
在你的情况下,它可能是这样的:
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)
答案 1 :(得分: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;