SQL删除重复项,两列之间的差异较大

时间:2014-02-28 17:43:28

标签: sql sql-server duplicates subtraction

我的桌子类似于:

ID    Value1      Value2
122   800         1600
122   800         1800
133   700         1500
154   800         1800
133   700         1500
188   700         1400
176   900         1500

从此表中,我想删除重复项(ID122的重复项),它们在value2和value1之间有较大的差异。

这意味着133 ID的位置我要保留第一行(122) 这意味着1800-800>1600-800 ID 133我希望保留其中任何一个,因为它们都有相同的差异。

ID    Value1      Value2
122   800         1600
122   800         1800  <------delete this row
133   700         1500  <------delete either this row or the other identical row
154   800         1800
133   700         1500  <------delete either this row or the other identical row
188   700         1400
176   900         1500

这个规模要大得多,所以我不能单独删除记录。

有没有办法编写一个语句来删除我的表中的所有重复项,其Value2 - Value1大于Value2 - Value1的副本?

1 个答案:

答案 0 :(得分:2)

SQL Server具有可更新CTE和子查询的这一强大功能。所以,你可以这样做:

with todelete as (
      select t.*,
             row_number() over (partition by id order by value2 - value1) as diff_seqnum
      from table t
     )
delete from todelete
    where diff_seqnum > 1;

也就是说,根据两个值的差异枚举每个id的行。然后,只保留序列号为1的行。

相关问题