表连接后如何避免多条记录

时间:2015-07-13 16:36:24

标签: sql-server join

我正在尝试加入两个表格。两个表都有列term_date,
和term_date记录不同。例如:
table1 FNAME LNAME DOB TERM_DATE1

  John  William 1/1/2001    2015/3/1  <br/>
    John  William 1/1/2001    9999/12/31 <br/>
     

table2 FNAME LNAME DOB TERM_DATE2
   John William 1/1/2001 2015/4/1
     John William 1/1/2001 9999/12/31

select t1.FNAME,t1.LNAME,t1.DOB,t1.TERM_DATE1,t2.TERM_DATE2 from table1 t1 join table2 t2 on t1.FNAME=t2.FNAME and t1.LNAME=t2.LNAME and t1.DOB=t2.DOB

然后我得到4条这样的记录          FNAME LNAME DOB TERM_DATE1 TERM_DATE2

 John  William 1/1/2001    2015/3/1  2015/4/1 <br/>
    John  William 1/1/2001    9999/12/31 2015/4/1 <br/>
    John  William 1/1/2001    2015/3/1  9999/12/31 <br/>
    John  William 1/1/2001    9999/12/31 9999/12/31 <br/>
     

但我只需要row1和row4,如何避免选择row2和row3。   谢谢。

1 个答案:

答案 0 :(得分:0)

通过使用row_number,我们可以忽略第2行和第3行

declare @table1 table ( FNAME varchar(10),  LNAME varchar(10),    DOB varchar(10),    TERM_DATE1 varchar(10))

insert into @table1 (FNAME,LNAME,DOB,TERM_DATE1)
values ('John','William','1/1/2001','2015/3/1'),('John','William','1/1/2001','9999/12/31')


declare @@table2 table ( FNAME varchar(10),  LNAME varchar(10),    DOB varchar(10),    TERM_DATE2 varchar(10))

insert into @@table2 (FNAME,LNAME,DOB,TERM_DATE2)
values ('John','William','1/1/2001','2015/4/1'),('John','William','1/1/2001','9999/12/31')

结果集:

;with cte as (
select t1.FNAME,t1.LNAME,t1.DOB,t1.TERM_DATE1,t2.TERM_DATE2,row_number()OVER (PARTITION BY DATEPART(YY,t1.TERM_DATE1),t1.DOB  order by t1.DOB)RN,
row_number()OVER (PARTITION BY DATEPART(YY,t2.TERM_DATE2),t1.DOB order by t1.DOB )R
from @table1 t1
join @@table2 t2
on t1.FNAME=t2.FNAME
and t1.LNAME=t2.LNAME
and t1.DOB=t2.DOB )

select FNAME,LNAME,DOB,TERM_DATE1,TERM_DATE2 from cte 
where RN = R