添加DELETE查询returns条重复记录 | SQL 服务器
Add DELETE to query that returns duplicate records | SQL Server
我需要你的帮助。
我有这个检测双工记录的查询:
SELECT
name, email, COUNT(*)
FROM
users
GROUP BY
name, email
HAVING
COUNT(*) > 1
所以我需要删除结果,所以我尝试了这个:
Delete FROM
users
GROUP BY
name, email
HAVING
COUNT(*) > 1
但不起作用。可以告诉我一个帮助吗?谢谢
试试这个 query:
DELETE
FROM users
WHERE ID NOT IN
(SELECT MAX(ID)
FROM users
GROUP BY name, email)
由于你的问题中没有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
我假设您想要只是删除重复行而不是所有与重复行相关的行。
你可以在这里使用ROW_NUMBER。您还没有为 USERS
table 提供整个架构,所以这里有一个例子
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
您可以将此查询更改为通用 Table 表达式,然后您可以从中删除
;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
只会删除重复的记录
我需要你的帮助。
我有这个检测双工记录的查询:
SELECT
name, email, COUNT(*)
FROM
users
GROUP BY
name, email
HAVING
COUNT(*) > 1
所以我需要删除结果,所以我尝试了这个:
Delete FROM
users
GROUP BY
name, email
HAVING
COUNT(*) > 1
但不起作用。可以告诉我一个帮助吗?谢谢
试试这个 query:
DELETE
FROM users
WHERE ID NOT IN
(SELECT MAX(ID)
FROM users
GROUP BY name, email)
由于你的问题中没有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
我假设您想要只是删除重复行而不是所有与重复行相关的行。
你可以在这里使用ROW_NUMBER。您还没有为 USERS
table 提供整个架构,所以这里有一个例子
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
您可以将此查询更改为通用 Table 表达式,然后您可以从中删除
;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
只会删除重复的记录