我有一个Customers表,其中包含名为CustomerID,CustomerNumber的列。我有一个Orders表,它引用了Customers中的CustomerID表。
我需要查找并删除订单表中没有订单的CustomerNumber的所有重复记录。
这就是我在客户中找到我的副本的方式,但我不知道如何通过订单表过滤掉然后删除额外的记录:
SELECT Name, CustomerNumber, COUNT(*) As DupeCount
FROM StagingCustomers
WHERE ManufacturerID=15
GROUP BY Name, CustomerNumber
HAVING COUNT(CustomerNumber) > 1
ORDER BY CustomerNumber
答案 0 :(得分:3)
添加EXISTS
子句以检查没有关系的任何记录:
SELECT Name, CustomerNumber, COUNT(*) As DupeCount
FROM StagingCustomers S
WHERE ManufacturerID=15
AND NOT EXISTS (SELECT 1 from Orders WHERE CustomerID = S.CustomerID)
GROUP BY Name, CustomerNumber
HAVING COUNT(CustomerNumber) > 1
ORDER BY CustomerNumber
修改强>
如何删除以下记录的示例。对于符合上述条件的每条记录,这会将IsDeleted
设置为1,并且不是customerid
每CustomerNumber
个UPDATE S
SET IsDeleted = 1
FROM StagingCustomers S
WHERE ManufacturerID=15
AND NOT EXISTS (SELECT 1 from Orders WHERE CustomerID = S.CustomerID)
AND CustomerID NOT IN (SELECT CustomerNumber, MIN(CustomerID)
FROM StagingCustomers
GROUP BY CustomerNumber)
GROUP BY Name, CustomerNumber
HAVING COUNT(CustomerNumber) > 1
ORDER BY CustomerNumber
。为了获得更清晰的答案,您需要提供表格布局和关系。
{{1}}
答案 1 :(得分:0)
这样的事情也可能有用:
SELECT Name, CustomerNumber, COUNT(*) As DupeCount
FROM StagingCustomers AS SC
LEFT JOIN ORDERS AS OD ON SC.CustomerID = OD.CustomerID
WHERE OD.CustomerID IS NULL AND ManufacturerID = 15
GROUP BY Name, CustomerNumber
HAVING COUNT(CustomerNumber) > 1
ORDER BY CustomerNumber
注意:没有测试代码,可能需要调整。