识别具有重复和唯一值的记录

时间:2015-06-18 20:10:41

标签: sql sql-server-2008 foreign-keys duplicates

我正在寻找外键不同的记录上的重复地址。这给了我重复:

select quoteID, insuredID, Address1, PolicyID
from quote
where 
address1 in(select address1 from quote group by address1 having count(address1) > 1)
and datalength(address1) <> 0
order by address1

我想过滤掉insuredID相同的所有记录。我真的需要在结果中保留quoteID,以便我可以调查问题帐户。我正在使用SQL Server 2008。

2 个答案:

答案 0 :(得分:0)

使用窗口功能。如果我理解你想要的逻辑:

select q.*
from (select q.*,
             min(insuredId) over (partition by address1) as minii,
             max(insuredId) over (partition by address1) as maxii
      from quote
      where datalength(address1) <> 0
     ) q
where minii <> maxii;

如果我的列错了,那么类似的东西可能就是你想要的。

我认为您有充分的理由使用datalength()而非len()

答案 1 :(得分:0)

如果我理解你,你只想找到那些记录具有相同地址但具有不同insuredId的记录。

以下查询应该执行此操作,首先它会像您一样获取所有重复的地址记录,然后通过加入它来仅提取具有这些地址的记录。然后按地址分组并且insuredId一起只抓取记录计数为1,任何大于1的意味着他们共享相同的insuredId和地址,这不是你想要的。

select quoteID, insuredID, Address1, PolicyID
from quote
    inner join (select Address1, insuredID
    from quote
        inner join (select address1 from quote where address1 IS NOT NULL group by address1 having count(address1) > 1) T1 on quote.address1 = T1.address1
    group by insuredID, Address1
    having count(address1) = 1) T2  on quote.address1 = T2.address1 and quote.insuredID = T2.insuredID
order by address1