请考虑以下情况
我有一张如下表格
Tag | Id | Client | ....and more columns
c 30 X
c 40 Y
c 50 X
c 60 A
c 30 B
c 40 C
d 50 D
d 70 E
d 80 X
d 90 Z
i 30 X
i 90 Z
i 100 X
i 40 M
我想从表中选择记录,如果tag = i 从结果集中删除下面的行
i 30 X
i 90 Z
这是因为id = 90的行已经出现tag = d和client = Z. 但是行
i 40 M
即使客户端= C已经出现id = 40,也不能删除,因为客户端列值不同。
DELETE FROM myTable
WHERE tag=i AND id IN( SELECT id FROM myTable t1
INNER JOIN myTable t2
ON t1.id=t2.id
WHERE tag=d or tag=c )
答案 0 :(得分:3)
根据您的规则,您可以使用CTE
跟WITH CTE AS
(
SELECT [Tag], [Id], [Client],
RN=ROW_NUMBER()OVER(PARTITION BY [Id], [Client] ORDER BY [Tag])
FROM dbo.Tags
)
DELETE FROM CTE
WHERE RN > 1
AND [Tag] = @Tag;
TAG ID CLIENT RN
i 30 X 2
i 90 Z 2
来检测和删除重复项:
{{1}}
删除这些记录:
{{1}}
答案 1 :(得分:1)
这应该可以解决问题......
declare @Tag as varchar(10)
set @Tag = 'i'
-- The select statement to view the record to be deleted
select MyTable.Tag,MyTable.Id,MyTable.Client,RecordToDelete.totalCount from [SampleDB].dbo.[MyTable]
inner join
(
SELECT
[Id]
,[Client],
TotalCount = count(id)
FROM [SampleDB].dbo.[MyTable]
group by id,Client
) as RecordToDelete
on RecordToDelete.Id=MyTable.Id and RecordToDelete.Client =MyTable.Client
where RecordToDelete.totalCount>1 and MyTable.Tag = @Tag
-- The delete statement
delete [SampleDB].dbo.[MyTable]
where MyTable.Tag = @Tag and MyTable.Id in (
--select MyTable.Tag,MyTable.Id,MyTable.Client,RecordToDelete.totalCount from [SampleDB].dbo.[MyTable]
select MyTable.Id from [SampleDB].dbo.[MyTable]
inner join
(
SELECT
[Id]
,[Client],
TotalCount = count(id)
FROM [SampleDB].dbo.[MyTable]
group by id,Client
) as RecordToDelete
on RecordToDelete.Id=MyTable.Id and RecordToDelete.Client =MyTable.Client
where RecordToDelete.totalCount>1 and MyTable.Tag = @Tag
)
答案 2 :(得分:1)
你可以试试这个:
DELETE FROM DUU WHERE EXISTS ( SELECT TAG,ID,CLIENT FROM ( SELECT TAG,ID,CLIENT FROM DUU A WHERE TAG IN ('I') AND EXISTS ( SELECT TAG,ID,CLIENT FROM DUU B WHERE TAG IN ('C') AND A.ID=B.ID AND A.CLIENT=B.CLIENT) UNION SELECT TAG,ID,CLIENT FROM DUU A WHERE TAG IN ('I') AND EXISTS ( SELECT TAG,ID,CLIENT FROM DUU B WHERE TAG IN ('D') AND A.ID=B.ID AND A.CLIENT=B.CLIENT) ) C WHERE DUU.TAG=C.TAG AND DUU.ID= C.ID AND DUU.CLIENT = C.CLIENT )
注意:DUU是表的名称。