在SQL中重复记录但保留ID

时间:2018-05-15 11:00:48

标签: sql duplicates

我有一个包含以下字段的表

  • id
  • entCode
  • postCode
  • addressLine1
  • addressLine2
  • addressLine3
  • addressLine4
  • addressLine5

identCode都是唯一的整数

我想要做的是重复数据删除,当然我可以这样做

select postCode, addressLine1, addressLine2, addressLine3, addressLine4, addressLine5
from addresses
group by postCode, addressLine1, addressLine2, addressLine3, addressLine4

然而,我还想做的是返回该地址的第一个ID和entCode,但我无法理解它 - 它将是select top 1 id, entcode但要匹配postCode +所有5个地址字段我不确定是否需要进行连接或其他操作。

提前致谢!

2 个答案:

答案 0 :(得分:1)

不确定我是否做得对,但也许您只是在寻找min()

select min(id), min(entCode), postCode, addressLine1, addressLine2, addressLine3, addressLine4, addressLine5
from addresses
group by postCode, addressLine1, addressLine2, addressLine3, addressLine4

答案 1 :(得分:0)

在几乎所有数据库中,您都可以使用row_number()

select a.*
from (select a.*,
             row_number() over (partition by postCode, addressLine1, addressLine2, addressLine3, addressLine4, addressLine5 order by id) as seqnum
      from addresses a
     ) a
where seqnum = 1;