旧的和当前位置在单排

时间:2014-11-24 03:39:21

标签: oracle

给出表:

empid empname location flag
1     kumar    Hyd      old
1     kumar    Chennai  current
2     mani     warangal  current

我想以下面的格式显示记录

empid empname oldlocation currentlocation
 1     kumar   Hyd           Chennai     
 2     mani      -            warangal

请帮我设计查询以获取上述格式的记录。

1 个答案:

答案 0 :(得分:2)

试试这个,你会得到你想要的结果,以防每个empid有一个旧标志。

select curr.empid,curr.empname,
nvl(old.oldlocation,'-') oldlocation,curr.current_location
from
  (
   select empid,empname,location oldlocation
   from empd where flag='old'
  ) old,
  (
   select empid,empname,location current_location
   from empd where flag='current'
  ) curr
where old.empid(+)=curr.empid;

如果您对empid有多个旧标记值,那么您可以使用下面给出的查询,该查询将提供当前以及最近的旧位置。

select xz.empid,xz.empname,xy.oldloc,xz.currloc
from(
  select empid,empname ,location oldloc
  from 
    (
       select empid,empname,location,flag,
       row_number() over (partition by empid order by rowid desc) rnk 
       from empd 
     ) where rnk=2) xy,
 (
  select empid,empname ,location currloc
  from 
    (
        select empid,empname,location,flag,
        row_number() over (partition by empid order by rowid desc) rnk 
        from empd 
     ) where rnk=1)xz
   where xy.empid(+)=xz.empid;