cte有时可能是记忆力的。以下SQL在其他数据库存在内存问题之前效果很好。
如何使用派生表重现Row_Number Over Partition的任何想法。
表A包含工作电话。 表B包含Id。 我们必须将表A与表B联系起来,以便在表B中找到重复项;使用手机作为重复标准。
这个SQL有效。我只是希望看到使用派生表的建议。
;WITH cte
AS (SELECT Row_number() OVER (PARTITION BY a.WorkPhone ORDER BY b.id DESC ) AS
rownumber
,
a.WorkPhone,
a.id
FROM TableB B
JOIN TableA a
ON b.GroupofLeadsid = a.id
WHERE b.GroupofLeads = @GroupofLeads
AND NOT a.WorkPhone IS NULL
AND a.WorkPhone <> '')
UPDATE b
SET b.deleteflag = 1
FROM TableB b
JOIN cte t
ON b.id = t.id
WHERE b.GroupofLeads = @GroupofLeads
AND rownumber > 1
答案 0 :(得分:0)
Update TableB
Set deleteflag = 1
From TableB As B
Join (
Select Row_Number() Over ( Partition By A.WorkPhone Order By B.Id Desc ) As RowNum
, A.WorkPhone, A.Id
, B.Id
From TableB As B1
Join TableA As A1
On A1.id = B1.GroupOfLeadsId
Where B1.GroupOfLeadsId = @GroupOfLeads
And A.WorkPhone <> ''
) As CTE
On CTE.Id = B.Id
Where CTE.RowNum > 1
另一种选择:
Update TableB
Set deleteflag = 1
Where Exists (
Select 1
From (
Select Row_Number() Over ( Partition By A.WorkPhone Order By B.Id Desc ) As RowNum
, B.Id
From TableB As B1
Join TableA As A1
On A1.id = B1.GroupOfLeadsId
Where B1.GroupOfLeadsId = @GroupOfLeads
And A.WorkPhone <> ''
) As CTE
Where CTE.RowNum > 1
And CTE.Id = TableB.Id
)