我有两个表:Product和ProductRateDetail。父表是Product。我在产品表中有重复记录,需要是唯一的。 ProductRateDetail表中有条目对应于product表中的重复记录。
不知何故,我需要更新ProductRateDetail表以匹配Product表中的原始(较旧)ID,然后从product表中删除重复项。我会手动完成,但有100个记录。即
之类的东西 UPDATE tbl_productRateDetail SET productID = (originalID from tbl_product)
然后像
DELETE from tbl_product WHERE duplicate ID
并且只删除最近添加的ID数据
示例:(抱歉无法解决此格式问题)
tbl_Product
select * from dbo.Product where ProductCode = '10003'
ProductID ProductTypeID ProductDescription ProductCode ProductSize
365 1 BEND DOUBLE FLANGED 10003 80mmX90deg
1354 1 BEND DOUBLE FLANGED 10003 80mmX90deg
tbl_ProductRateDetail
SELECT * FROM [MSTS2].[dbo].[ProductRateDetail] WHERE ProductID in (365,1354)
ProductRateDetailID ProductRateID ProductID UnitRate
365 1 365 16.87
1032 5 365 16.87
2187 10 365 16.87
2689 11 365 16.87
3191 12 365 16.87
7354 21 1354 21.30
7917 22 1354 21.30
8480 23 1354 21.30
9328 25 1354 21.30
9890 26 1354 21.30
10452 27 1354 21.30
答案 0 :(得分:1)
这样的事情应该有效:
1)更新引用重复项的产品详细信息
UPDATE tbl_productRateDetail d
SET productID = (SELECT MIN(p0.productID)
FROM tbl_product p0
JOIN tbl_product p1
ON p1.ProductTypeID = p0.ProductTypeID
AND p1.ProductDescription = p0.ProductDescription
AND p1.ProductCode = p0.ProductCode
AND p1.ProductSize = p0.ProductSize
WHERE p1.productID = d.productId)
WHERE productID IN (SELECT productID
FROM tbl_product
WHERE (ProductTypeID,
ProductDescription,
ProductCode,
ProductSize) IN
(SELECT ProductTypeID,
ProductDescription,
ProductCode,
ProductSize
FROM tbl_product
GROUP BY ProductTypeID,
ProductDescription,
ProductCode,
ProductSize
HAVING COUNT(*) > 1));
2)检测重复
DELETE FROM tbl_product p0
WHERE productID <> (SELECT MIN(productID)
FROM tbl_product p1
WHERE p1.ProductTypeID = p0.ProductTypeID
AND p1.ProductDescription = p0.ProductDescription
AND p1.ProductCode = p0.ProductCode
AND p1.ProductSize = p0.ProductSize);
答案 1 :(得分:1)
未经测试,因此语法可能会出现一些错误。
首先,从分组的产品ID中取出最小产品ID,然后更新ProductRateDetail中的记录
UPDATE prd1
SET prd1.ProductID = p2.ProductID
FROM ProductRateDetail prd1
INNER JOIN Product p1 ON
p1.ProductID = prd1.ProductID
INNER JOIN
(
SELECT MIN(ProductID) AS ProductID, ProductTypeID, ProductDescription, ProductCode, ProductSize
FROM Product
GROUP BY ProductTypeID, ProductDescription, ProductCode, ProductSize
) p2 ON
p1.ProductTypeID = p2.ProductTypeID AND
p1.ProductDescription = p2.ProductDescription AND
p1.ProductCode = p2.ProductCode AND
p1.ProductSize = p2.ProductSize
然后,删除不是“已选择”ID
的分组产品DELETE p1
FROM Product p1
INNER JOIN
(
SELECT MIN(ProductID) AS ProductID, ProductTypeID, ProductDescription, ProductCode, ProductSize
FROM Product
GROUP BY ProductTypeID, ProductDescription, ProductCode, ProductSize
) p2 ON
p1.ProductTypeID = p2.ProductTypeID AND
p1.ProductDescription = p2.ProductDescription AND
p1.ProductCode = p2.ProductCode AND
p1.ProductSize = p2.ProductSize AND
p1.ProductID != p2.ProductID