尝试在SQL Server 2017中使用CTE查找重复项

时间:2018-04-12 21:09:25

标签: sql-server duplicates common-table-expression

我正在尝试修改下面找到的代码,以便让我找到可以删除RowOrder>行的重复项。 1.我收到错误,指出最后一行')'附近的语法不正确。我不确定我做错了什么,请帮忙。提前谢谢!

original source

WITH OrderedRows
AS
(
SELECT  ID, Carrier, ClaimDate, EmpID, ClaimNumber, LossNumber, TaskID, 
TaskType, TaskGroup, LetterDetails, Outlier, BeginTime, 
EndTime,TemplateUsed, Increment, ROW_NUMBER() OVER (PARTITION BY Carrier, 
ClaimDate, EmpID, ClaimNumber,LossNumber, TaskID, TaskType, TaskGroup, 
LetterDetails, Outlier, BeginTime, EndTime,TemplateUsed, Increment ORDER BY 
ID) as RowOrder
FROM    BillingStaging
)
DELETE FROM OrderedRows
WHERE RowOrder > 1 

2 个答案:

答案 0 :(得分:3)

您刚刚定义了CTE,但是您没有使用它,您需要添加delete from声明

WITH OrderedRows
AS
(
     SELECT  ID, Carrier, ClaimDate, EmpID, ClaimNumber, LossNumber, TaskID, 
     TaskType, TaskGroup, LetterDetails, Outlier, BeginTime, 
     EndTime,TemplateUsed, Increment, 
     ROW_NUMBER() OVER (PARTITION BY Carrier, ClaimDate, EmpID,ClaimNumber,LossNumber, TaskID, TaskType, TaskGroup,LetterDetails, Outlier, BeginTime, EndTime,TemplateUsed, Increment ORDER BY ID) as RowOrder
 FROM    BillingStaging
)
DELETE FROM OrderedRows
WHERE RowOrder > 1 

答案 1 :(得分:0)

唉。弄清楚了。原来的答案是对的。在使用DELETE语句之前,我试图让语法正确,但是通过放置SELECT * FROM OrderedRows,它就可以了。谢谢您的帮助。我已经做了一段时间了。

这有效

WITH OrderedRows 
AS
(
SELECT
    ID, ClaimDate, EmpID, ClaimNumber, TaskType, BeginTime, EndTime, Increment,
    ROW_NUMBER() OVER (PARTITION BY ID, ClaimDate, EmpID, ClaimNumber, TaskType, BeginTime,
        EndTime, Increment ORDER BY ID) as RowOrder
FROM BillingStaging
)
SELECT * FROM OrderedRows