我需要您的帮助。
我有此查询可检测双工记录:
SELECT
name, email, COUNT(*)
FROM
users
GROUP BY
name, email
HAVING
COUNT(*) > 1
所以我需要删除结果,所以我已经尝试了:
Delete FROM
users
GROUP BY
name, email
HAVING
COUNT(*) > 1
但不起作用。能告诉我一个帮助吗?谢谢。
答案 0 :(得分:2)
尝试以下query:
DELETE
FROM users
WHERE ID NOT IN
(SELECT MAX(ID)
FROM users
GROUP BY name, email)
答案 1 :(得分:1)
由于您的问题中没有ID列(主键),因此假设没有ID列。 因此,CTE下面将删除重复的记录。
;WITH CTE AS (
SELECT name
, email
, ROW_NUMBER() Over(Partition by name, email Order by(Select 1)) as Sno
FROM users
)
DELETE FROM CTE WHERE SNO>1
答案 2 :(得分:0)
我假设您要仅删除重复行,而不是与重复行有关的所有行。
您可以在此处使用ROW_NUMBER。您尚未提供USERS
表的整个架构,因此这里有一个示例
CREATE TABLE dbo.Users(
Id INT IDENTITY(1,1)
,[Name] NVARCHAR(50)
,eMail NVARCHAR(50)
,DateCreated DATETIME
)
SELECT
Id
,[Name]
,eMail
,DateCreated
,RN = ROW_NUMBER()OVER(PARTITION BY Name, eMail ORDER BY DateCreated ASC)
FROM dbo.Users
您可以将此查询更改为通用表表达式,然后从中删除
;WITH cteDups
AS(
SELECT
Id
,[Name]
,eMail
,DateCreated
,RN = ROW_NUMBER()OVER(PARTITION BY Name, eMail ORDER BY DateCreated ASC)
FROM dbo.Users
)
DELETE FROM cteDups WHERE RN > 1
RN > 1
仅删除重复的记录