如果前一个在特定列中具有相同值,则如何删除行

时间:2010-08-13 11:29:16

标签: sql sql-server-2005

假设我有一张看起来像这样的表:

-------------------------------
id|column2|column3   |column4
-------------------------------
1  value1  somevalue  somevalue
2  value2  somevalue  somevalue
3  value2  somevalue  somevalue <----- I want this column deleted
4  value3  somevalue  somevalue

如您所见,我想删除当前行和上一行在column2中具有相同值的行。

3 个答案:

答案 0 :(得分:5)

我会尝试像

这样的东西
DELETE FROM Table t1 
WHERE EXISTS (SELECT 1 from Table t2 
              WHERE t1.Column2 = t2.Column2 
              AND t2.Id + 1 = t1.Id) 

对于您的特定查询,我会使用t2.Id + 1 = t1.Id而不是t2.Id < t1.Id,因为这会删除任何出现,而不是仅连续的条目。

答案 1 :(得分:1)

DELETE FROM Table t1
WHERE EXISTS (SELECT 1 from Table t2
              WHERE t1.Column2 = t2.Column2
              AND t1.Column3 = t2.Column3                  
              AND t1.Column4 = t2.Column4
              AND t2.Id > t1.Id)

如果您需要仅按一个字段比较行

DELETE FROM Table t1
WHERE EXISTS (SELECT 1 from Table t2
              WHERE t1.Column2 = t2.Column2
              AND t2.Id > t1.Id)

答案 2 :(得分:0)

delete from table_name where rowid in(
select a.rowid 
from (
      select rowid,
            row_number() over (partition by column_name_having_duplicates order by                  column_name_having_duplicates)rnk 
from table_name a
)a
where a.rnk>1);