t-sql - 仅删除第二个值

时间:2010-12-08 20:56:41

标签: sql sql-server tsql

我想运行一个sql语句,它只会删除第二个值,例如

delete from table1 where condition1

我希望此语句仅删除第二个值

我怎么能做到这一点?

我想澄清一下。我有一个名为field1的字段,它是一个自动编号,它是一个主键,它会递增。我想删除包含更大数字的记录

4 个答案:

答案 0 :(得分:3)

您还可以使用SQL服务器的ROW_NUMBER()函数对每一行进行编号,并根据您在内部查询中的自定义顺序使用此编号来隔离第二项删除项({{1} })。这提供了很大的灵活性。

over (ORDER BY <myKey> asc)

答案 1 :(得分:1)

您是否只想删除最后一个副本,或者只删除第一个副本?

除了第一个之外的所有人:( 已编辑根据@ Martin的建议使用CTE。)

with target as (select * from table1 where condition1)
delete from target goner
 where exists (select * from target keeper
                where keeper.field1 < goner.field1)

换句话说,如果存在另一个匹配记录较低的field1,请删除此记录。

修改 仅删除最后一个:

with target as (select * from table1 where condition1)
delete from target goner
 where exists (select * from target keeper
                where keeper.field1 < goner.field1)
   and not exists (select * from target missing
                    where missing.field1 > goner.field1)

换句话说,如果有另一个匹配记录与较低的field1,并且没有匹配的记录与较高的field1,那么我们有最高的重复,所以核对它。

答案 2 :(得分:0)

试试这个:

DELETE MyTable 
FROM MyTable
LEFT OUTER JOIN (
   SELECT MIN(id) as id, Col1, Col2, Col3 
   FROM MyTable 
   GROUP BY Col1, Col2, Col3
) as KeepRows ON
   MyTable.id= KeepRows.id
WHERE
   KeepRows.RowId IS NULL

<强>更新

虽然这可能不像@Jeffrey那样“漂亮”,但它的确有效。据我所知,@ Jeffrey's没有。请参阅下面的sql(删除替换为SELECT *以进行演示):

WITH TEMP as
(
  SELECT 1 as id,'A' as a,'Z' as b
  UNION
  SELECT 2,'A','Z'
  UNION
  SELECT 3,'B','Z'
  UNION
  SELECT 4,'B','Z'
)

SELECT *
FROM TEMP
LEFT OUTER JOIN (
   SELECT MIN(id) as id, a, b
   FROM TEMP 
   GROUP BY a, b
) as KeepRows ON
   temp.id= KeepRows.id
WHERE
   KeepRows.id IS NULL

答案 3 :(得分:0)

已经有一段时间了(所以我的语法不太正确),这可能不是最佳解决方案,但“学术”答案可能是这样的:

delete from table1 where condition1
and field1 = (select max(field1) from table1 where condition1)