兄弟,这是找出重复数据的方法之一,试试吧=)
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