1

我的数据库中有这张表:

tblAgencies
----------------------
AgencyID (PK)
VendorID
RegionID
Name
Zip

长话短说,我不小心将我的整个表格复制到了自身中——所以我表格中的每一行都有一个副本。

但是由于我的AgencyID字段是身份并自动递增,我需要根据所有其他字段查找重复项,因为AgencyID它是唯一的。

有谁知道我该怎么做?

4

8 回答 8

3

这将保留最旧的 AgencyID 值,否则将删除任何重复项。

;WITH x AS 
(
  SELECT *, rn = ROW_NUMBER() OVER 
    (PARTITION BY VendorID, RegionID, Name, Zip
    ORDER BY AgencyID) FROM dbo.tblAgencies
)
DELETE x WHERE rn > 1;

不过要小心;如果其他表引用 AgencyID并且它们已经获得了您的任何更新的错误值,这可能不起作用。

于 2013-11-14T22:42:11.880 回答
1

最简单的解决方案,使用 select distinct 进入临时表,然后重新加载原始

于 2013-11-14T22:22:09.297 回答
0
;with CTE 
AS
(SELECT MAX(AgencyID) AgentID,VendorID ,
RegionID ,
Name ,
Zip  FROM tblAgencies
GROUP BY VendorID ,
RegionID ,
Name ,
Zip 
HAVING COUNT(*) > 1)

DELETE FROM tblAgencies WHERE  EXISTS  (SELECT 1 FROM CTE
WHERE  AgentID = tblAgencies.AgencyID)
于 2013-11-15T05:59:15.793 回答
0

也许这会有所帮助:如何在存在主键的情况下删除重复项?

于 2013-11-16T09:54:34.933 回答
0

很多答案会给你你想要的,但没有必要使用 CTE 或做任何分组,最简单的方法就是:

delete   t1
from     tblAgencies t1
join     tblAgencies t2
on       t1.VendorId = t2.VendorId
and      t1.RegionId = t2.RegionId
and      t1.Name = t2.Name
and      t1.Zip = t2.Zip
and      t1.AgencyId > t2.AgencyId
于 2013-11-15T14:33:36.717 回答
0

如果所有其他列的组合是唯一的,则此查询将为您提供重复项:

select * from mytable t1
where exists
         (select * from mytable t2 
         where t1.VendorID = t2.VendorID 
         and t1.RegionID = t2.RegionID 
         and and t1.Name = t2.Name 
         and t1.Zip = t2.Zip 
         and t1.AgencyID > t2.AgencyID)
于 2013-11-14T22:24:11.117 回答
0

这应该为您提供所有具有重复值的行,除了最小的机构 ID 行。

select *
  from tblAgencies
  where AgencyID not in (select min(AgencyID)
                           from tblAgencies
                           group by VendorID, RegionID, Name, Zip)

编辑:添加SQLFiddle

于 2013-11-14T22:24:28.987 回答
0
;with CTE 
AS
 (
   SELECT ID_Column, rn = ROW_NUMBER() OVER (PARTITION BY Column1, Column2, Column3... ORDER BY ID ASC)
  FROM T
)
DELETE FROM CTE 
WHERE rn >= 2
于 2013-11-14T22:45:54.290 回答