2

我有一张需要删除重复项的表。但是,该表的设计使每个客户都可以拥有相同的物品。这是一个屏幕截图,例如:

在此处输入图像描述

当我尝试删除重复项时,我还会得到两个客户相同的书号。绿色区域显示实际重复,但蓝色显示不重复的书籍,因为客户可以借用相同的书籍。

如何仅删除每个客户的行相同的位置?所以绿色区域。

这是我的代码:如果两个客户的书号相同,它就不起作用。

WITH CTE AS
(
SELECT  *, 
ROW_NUMBER() OVER (PARTITION BY BookNumber ORDER BY BookNumber DESC) AS DUPS
FROM Store.Books 
)

SELECT * FROM CTE WHERE DUPS > 1
4

3 回答 3

1

下面的查询应该给你一个包含 customerIDs 的所有重复书号的列表,你需要做的只是一个简单的删除语句,其结果是删除重复记录

SELECT count(bookNumber), booknumber, customerID FROM TableName GROUP BY booknumber, customerID having count(booknumber)> 1
于 2013-08-16T07:33:39.563 回答
1
WITH CTE AS
(
SELECT  *, 
ROW_NUMBER() OVER (PARTITION BY BookNumber, Customerid ORDER BY BookNumber) AS DUPS
FROM Store.Books 
)
SELECT * FROM CTE WHERE DUPS > 1
-- if you want to delete, replace last line with this:
--DELETE FROM CTE WHERE DUPS > 1

我应该提到不需要按书号 desc 的顺序,所以我删除了“desc”部分

于 2013-08-16T07:43:45.897 回答
0

兄弟,这是找出重复数据的方法之一,试试吧=)

DECLARE @tempTable TABLE(
CustomerID SMALLINT,
BookLoan NVARCHAR(255),
BookNumber INT,
BookAuthor NVARCHAR(255)
)

INSERT INTO @tempTable Values(112,'Clash Of Titans',12345,'Dick VanDyke ')
INSERT INTO @tempTable Values(112,'Clash Of Titans',12345,'Dick VanDyke ')
INSERT INTO @tempTable Values(112,'Clash Of Titans',23457,'Dick VanDyke ')
INSERT INTO @tempTable Values(112,'History of Soda',99899,'Brian Adams  ')

Select *,Count(*) 'Occurrance' From @tempTable Group by 
CustomerID,BookLoan,BookNumber,BookAuthor having count(*) > 1


Delete from @temptable
where CustomerID = (Select customerID From @tempTable Group by
CustomerID,BookLoan,BookNumber,BookAuthor having count(*) > 1)
AND BookLoan = (Select BookLoan From @tempTable Group by 
CustomerID,BookLoan,BookNumber,BookAuthor having count(*) > 1)
AND BookNumber = (Select BookNumber From @tempTable Group by 
CustomerID,BookLoan,BookNumber,BookAuthor having count(*) > 1)
AND BookAuthor = (Select BookAuthor From @tempTable Group by 
CustomerID,BookLoan,BookNumber,BookAuthor having count(*) > 1)

Select * from @tempTable

或替代方式如下

DECLARE @tempTable TABLE(
CustomerID SMALLINT,
BookLoan NVARCHAR(255),
BookNumber INT,
BookAuthor NVARCHAR(255)
)

INSERT INTO @tempTable Values(112,'Clash Of Titans',12345,'Dick VanDyke ')
INSERT INTO @tempTable Values(112,'Clash Of Titans',12345,'Dick VanDyke ')
INSERT INTO @tempTable Values(112,'Clash Of Titans',23457,'Dick VanDyke ')
INSERT INTO @tempTable Values(112,'History of Soda',12345,'Brian Adams  ')

;WITH CTE AS
(
SELECT  *, 
ROW_NUMBER() OVER (PARTITION BY CustomerID, BookLoan,BookNumber,BookAuthor 
ORDER BY BookNumber) AS DUPS
FROM @tempTable
)
DELETE FROM @tempTable
WHERE CustomerID = (SELECT CustomerID FROM CTE WHERE DUPS > 1)
AND BookLoan = (SELECT BookLoan FROM CTE WHERE DUPS > 1)
AND BookNumber = (SELECT BookNumber FROM CTE WHERE DUPS > 1)
AND BookAuthor = (SELECT BookAuthor FROM CTE WHERE DUPS > 1)

SELECT * FROM @tempTable
于 2013-08-16T09:02:43.357 回答