【发布时间】:2010-08-17 21:56:14
【问题描述】:
搜索 stackoverflow.com 后,我发现了几个问题,询问如何删除重复项,但都没有解决速度问题。
在我的例子中,我有一个包含 10 列的表,其中包含 500 万个精确的行重复。此外,我在 10 列中的 9 列中至少有一百万行重复。我目前的技术(到目前为止)需要 3 小时 来删除这 500 万行。这是我的过程:
-- Step 1: **This step took 13 minutes.** Insert only one of the n duplicate rows into a temp table
select
MAX(prikey) as MaxPriKey, -- identity(1, 1)
a,
b,
c,
d,
e,
f,
g,
h,
i
into #dupTemp
FROM sourceTable
group by
a,
b,
c,
d,
e,
f,
g,
h,
i
having COUNT(*) > 1
接下来,
-- Step 2: **This step is taking the 3+ hours**
-- delete the row when all the non-unique columns are the same (duplicates) and
-- have a smaller prikey not equal to the max prikey
delete
from sourceTable
from sourceTable
inner join #dupTemp on
sourceTable.a = #dupTemp.a and
sourceTable.b = #dupTemp.b and
sourceTable.c = #dupTemp.c and
sourceTable.d = #dupTemp.d and
sourceTable.e = #dupTemp.e and
sourceTable.f = #dupTemp.f and
sourceTable.g = #dupTemp.g and
sourceTable.h = #dupTemp.h and
sourceTable.i = #dupTemp.i and
sourceTable.PriKey != #dupTemp.MaxPriKey
关于如何加快速度或更快的方法的任何提示?请记住,对于不完全重复的行,我将不得不再次运行它。
非常感谢。
更新:
我不得不停止第 2 步在 9 小时标记处运行。
我尝试了 OMG Ponies 的方法,只用了 40 分钟就完成了。
我用 Andomar 的批量删除尝试了我的第 2 步,它在我停止它之前运行了 9 个小时。
更新:
使用 OMG Ponies 的方法运行一个具有较少字段的类似查询以消除一组不同的重复项,并且该查询仅运行了 4 分钟(8000 行)。
下次有机会我会尝试 cte 技术,但是,我怀疑 OMG Ponies 的方法很难被击败。
【问题讨论】:
-
对上面的查询进行了一些简单的优化 - 您不需要在顶部查询的
SELECT中包含 a、b、c 等 - 您只需要 PriKey,然后删除 HAVING - 然后,在第二个查询中只需DELETE FROM sourceTable WHERE PriKey NOT IN (SELECT DT.MaxPriKey FROM #dupTemp DT)
标签: sql sql-server sql-server-2008 etl