我希望从连接表中获取最新日期,其中包含2列中的唯一值。我该怎么做呢?我也尝试过排名(但John排名相同)并尝试了rownum = 1,但由于某种原因我仍然得到相同的结果
Name ID Email DeptNo DeptScore OnDate
John A46 john@doe.com 100 50 5/11/2011
John A46 johndoe@aol.com 200 75 7/21/2015
Alice B33 alice@hotmail.com 100 50 4/15/2014
我想得到以下内容:
Name ID Email DeptNo DeptScore OnDate
John A46 johndoe@aol.com 200 75 7/21/2015
Alice B33 alice@hotmail.com 100 50 4/15/2014
我的查询
select distinct e.name, e.id, e.email, d.deptno, d.deptscore, d.ondate
from
emp e
inner join dept d on
d.deptno = e.dnum
and d.ondate = e.livedate
and d.ondate = (select max(m.ondate)
from dept m
where d.ondate = m.ondate)
--where e.id in ('A46','B33')
答案 0 :(得分:3)
尝试使用以下查询,它将解决您的问题。
select name,
id,
email,
deptno,
deptscore,
ondate
from (select e.name,
e.id,
e.email,
d.deptno,
d.deptscore,
d.ondate,
rank() over(partition by e.id,e.name order by d.ondate desc) rn
from emp e join
dept d
on d.deptno = e.dnum and d.ondate = e.livedate
) s
where rn = 1;
输出:
NAME ID EMAIL DEPTNO DEPTSCORE ONDATE
John A46 johndoe@aol.com 200 75 21-JUL-15
Alice B33 alice@hotmail.com 100 50 15-APR-14