如何从同一个表中删除行?

时间:2011-02-18 23:30:56

标签: sql sql-server

我有一个记录请求和响应的表。该表格包含时间戳列和包含2个可能值的交易类型列: req resp 。无论原因如何,我都有 resp 行没有匹配的 req 行。

我正在尝试删除所有 resp 行,这些行没有匹配的 req 行,并且具有相同的时间戳。有任何想法吗?

伪代码需要的是:

删除中的所有行,其中事务类型等于 resp ,并且没有匹配的 req 行具有相同的时间戳。

5 个答案:

答案 0 :(得分:3)

试试这个:

Delete Table t
Where TxType = 'resp'
  And Not Exists
   (Select * From Table
    Where timestamp = t.timestamp
       and TxType = 'req')

(在交易内部,如果失败,你可以回滚!)

哦,是的,Chris Lively从下面提出了一个很好的观点..当你提到“ TimeStamp ”时,你是在说一般吗?或者你在谈论保证是唯一的SQL Server时间戳数据类型?如果是前者,并且您实际上正在使用日期时间或其他类似的,那么您确定在同一时间不能有两个或更多不同的请求吗?

答案 1 :(得分:1)

类似以下内容应该这样做。

delete mytable
  from mytable t1
     left outer join mytable t2 
         and (t2.TimeStamp = t1.TimeStamp)
         and (t2.TransactionType = 'req')
  where (t2.TimeStamp is null)
    and (t1.TransactionType = 'resp')

看了这个之后,这两个记录之间的关系真的是一个时间戳吗?在我看来,时间戳会有所不同,而是你有一些其他键将两者联系在一起。

答案 2 :(得分:1)

这应该对你有用

delete T1
from @T as T1
where
  T1.[Type] = 'resp' and
  T1.[TimeStamp] not in (select [TimeStamp]
                         from @T as T2
                         where T2.[Type] = 'req')

还有一些测试代码

declare @T table ([TimeStamp] datetime, [Type] varchar(5))

insert into @T values
('2001-01-01', 'req'),
('2001-01-01', 'resp'),
('2002-01-01', 'resp'),
('2003-01-01', 'req')

print 'Before delete'
select *
from @T

delete T1
from @T as T1
where
  T1.[Type] = 'resp' and
  T1.[TimeStamp] not in (select [TimeStamp]
                         from @T as T2
                         where T2.[Type] = 'req')

print 'After delete'
select *
from @T

输出

(4 row(s) affected)
Before delete
TimeStamp               Type
----------------------- -----
2001-01-01 00:00:00.000 req
2001-01-01 00:00:00.000 resp
2002-01-01 00:00:00.000 resp
2003-01-01 00:00:00.000 req

(4 row(s) affected)

(1 row(s) affected)

After delete
TimeStamp               Type
----------------------- -----
2001-01-01 00:00:00.000 req
2001-01-01 00:00:00.000 resp
2003-01-01 00:00:00.000 req

(3 row(s) affected)

答案 3 :(得分:1)

;WITH T AS
(
SELECT *, RANK() OVER (PARTITION BY [TimeStamp] ORDER BY [Type]) RN
FROM YourTable
)
DELETE FROM T 
WHERE Type='resp' AND RN=1

答案 4 :(得分:0)

DELETE FROM YourTable
WHERE Timestamp IN (
  SELECT Timestamp FROM YourTable WHERE TransactionType = 'resp'
  EXCEPT
  SELECT Timestamp FROM YourTable WHERE TransactionType = 'req'
)