请参阅下面的DDL:
create table #address (ID int IDENTITY, housenumber varchar(30), street varchar(30), town varchar(30), county varchar(30), postcode varchar(30), primary key (id))
insert into #address (housenumber,street,town,county,postcode) values ('1', 'The Street', 'Lincoln', null, 'LN21AA')
insert into #address (housenumber,street,town,county,postcode) values ('1', 'The Street', 'Lincoln', null, 'LN21AA')
insert into #address (housenumber,street,town,county,postcode) values ('1', 'The Street', 'Lincoln', 'Lincolnshire', 'LN21AA')
和下面的SQL:
select #address .id as masterid, address2.id as childid from #address inner join #address as address2 on
#address.housenumber=address2.housenumber and #address.street=address2.street
and #address.town=address2.town
and #address.county=address2.county
and #address.postcode=address2.postcode
where #address.id<address2.id
我正在尝试识别重复项。
&#39;县&#39;有时为null,其他为null。上面的查询不返回任何行。
我试过这个命令:
set ansi_nulls off
然而,它没有任何区别。我意识到我可以这样做:
select #address .id as masterid, address2.id as childid from #address inner join #address as address2 on
#address.housenumber=address2.housenumber and #address.street=address2.street
and #address.town=address2.town
and ((#address.county=address2.county) or (#address.county is null and address2.county is null))
and #address.postcode=address2.postcode
但是,我很想知道为什么将ansi nulls设置为off可以让你这样做:
select * from #address where county=null
返回两行。但是,当ANSI NULL关闭时,我的第一个查询不返回任何行。为什么ANSI NULLS对ON子句没有影响。
我花了20分钟谷歌搜索,但我没有找到答案。 其中#address.id
答案 0 :(得分:1)
您可以使用group by
识别重复项。当有两个值时,以下内容返回id:
select housenumber, street, town, country postcode, count(*) as cnt,
min(a.id) as masterid, max(a.id) as childid
from #address a
group by housenumber, street, town, country postcode
having count(*) >= 2;
获取给定地址的所有ID需要额外的连接或时髦的字符串聚合。