在左连接中使用Oracle rank()

时间:2014-12-15 19:20:54

标签: sql oracle

当我自己运行这个子查询时:

select * 
from (select rpt_nbr, iteration, seq_nbr, emp_id_key, rank() over
     (partition by   emp_id_key order by iteration, seq_nbr) rk 
      from SJTCAPP.LAB_RPT_SPEC_EMP where rpt_nbr = 1572413) 
where rk = rownum

我得到了一个很好的结果,每次迭代只返回1 emp_id_key seq_nbr,即使可以分配多个emp_id_key。但是,当我将其添加到我的查询的其余部分时,这很好:

select * from 

SJTCAPP.LAB_RPT r 
left join SJTCAPP.LAB_RPT_SPEC s on s.rpt_nbr = r.rpt_nbr
left join (select * from
    (select rpt_nbr, iteration, seq_nbr, emp_id_key, rank() over (partition by emp_id_key order  
         by iteration, seq_nbr) rk from SJTCAPP.LAB_RPT_SPEC_EMP ) where rk = rownum)
         se on se.rpt_nbr = s.rpt_nbr and se.seq_nbr = s.seq_nbr and se.iteration = s.iteration
left join sjtcapp.employee tech on tech.emp_id_key = se.emp_id_key

我为tech.emp_id_key join

获取了一个NULL值

更新

select * from (select rpt_nbr, iteration, seq_nbr, emp_id_key, rank() over (partition by emp_id_key order by iteration, seq_nbr ) rk from SJTCAPP.LAB_RPT_SPEC_EMP where rpt_nbr = 1572413)  where rk = rownum and rpt_nbr = 1572413

以上查询也提供了“好”的信息。结果。

RPT_NBR ITERATION   SEQ_NBR EMP_ID_KEY  RK
1572413 1   1   44746   1
1572413 1   2   44746   2

之前我在这里进行了更多简单的加入,并收到了具有各个技术人员姓名的正确查询。唯一的问题是,如果分配了多个,则会导致重复,这就是我添加等级子查询的原因。

2 个答案:

答案 0 :(得分:0)

如果约束迭代并且seq_nbr是唯一的,则可以使用exists而不是rank

SELECT
  rpt_nbr,
  iteration,
  seq_nbr,
  emp_id_key
FROM
  SJTCAPP.LAB_RPT_SPEC_EMP emp
WHERE
  NOT EXISTS
    (
      SELECT
        *
      FROM
        SJTCAPP.LAB_RPT_SPEC_EMP emp2
      WHERE
        emp2.emp_id_key = emp.emp_id_key AND
        emp2.iteration < emp.iteration AND
        emp2.seq_nbr < emp.seq_nbr
    )

答案 1 :(得分:0)

我最终回到了使用GROUP BY

left join (
    select min(rpt_nbr) as rpt_nbr, min(iteration) as iteration, min(seq_nbr) as seq_nbr, min(emp_id_key) as emp_id_key from LAB_RPT_SPEC_EMP group by rpt_nbr, iteration, seq_nbr
    ) se
    on se.rpt_nbr = s.rpt_nbr and se.seq_nbr = s.seq_nbr and se.iteration = s.iteration