Sql查询重复列具有不同的有效开始日期

时间:2016-03-11 08:34:04

标签: sql oracle

我有一个表x_person和x_person_name。结构为:

x_person

eff_start_date eff_end_date   person_number 

01-jan-1990     31-dec-4712     2
01-feb-1990     31-dec-4712     2

01-jan-1990     31-dec-4712     1


x_person_name


eff_start_date eff_end_date   person_number  name

01-jan-1990     31-dec-4712     2             freida 
01-feb-1990     31-dec-4712     2             sam

01-jan-1990     31-dec-4712     1             isha

现在我想检查这两个表中同一个员工是否有相同的有效开始日期。对于那些我没有创建查询的人

select * from 
(
select distinct min(x.Effective_Start_Date) over(partition by x.person_number) Effective_Start_Date_name, y.Effective_Start_Date,x.person_number
from  x_person_name x,x_person y where 
x.person_number=y.person_number 
) 
where Effective_Start_Date_name <> Effective_Start_Date;

但是这个查询不适用于例如2号人物,尽管他们是2个不同的人,并且在x_person中有2个不同的记录。但它仍然在输出中传达。

输出我

effective_start_date  y.effective_start_date person_number
01-jan-1990            01-feb-1990            2

虽然这不应该来。

2 个答案:

答案 0 :(得分:0)

假设您需要x_person中不匹配x_person_name的行,这可能会有所帮助:

select *
from x_person p
  left outer join x_person_name pn
  ON (
      p.person_number = pn.person_number and
      p.eff_start_date = pn.eff_start_date
     )
where pn.person_number is null

答案 1 :(得分:0)

with x_perosn(eff_start_date, eff_end_date, person_number)
     as (select to_date('01-jan-1990'), to_date('31-dec-4712'), 2 from dual
         union all
         select to_date('01-feb-1990'), to_date('31-dec-4712'), 2 from dual
         union all
         select to_date('01-jan-1990'), to_date('31-dec-4712'), 1 from dual)
   , x_person_name(eff_start_date
                 , eff_end_date
                 , person_number
                 , name)
     as (select to_date('01-jan-1990'), to_date('31-dec-4712'), 2, 'freida' from dual
         union all
         select to_date('01-feb-1990'), to_date('31-dec-4712'), 2, 'sam' from dual
         union all
         select to_date('01-jan-1990'), to_date('31-dec-4712'), 1, 'isha' from dual)                                        
select * from (         
select  min(eff_start_date) over( partition by person_number) ed,y.* from x_person_name y
        ) t1 where not exists (select 1 from x_perosn where person_number= t1.person_number and ed = eff_start_date)

我认为你正在寻找一种叫做反连接的东西。仅返回table1中的行,表2中没有行。