我有一张桌子:
UserA UserB UserBB UserAA
例如:
1 2 2 1
1 3 3 1
2 1 1 2
2 4 4 2
2 5 5 2
5 2 2 5
我想要实现的是删除行(重复项),例如只留下行,例如:
1 2 2 1
1 3 3 1
2 4 4 2
2 5 5 2
2 1 1 2 -> deleted because there is already 1 2 2 1
5 2 2 5 -> deleted because there is already 2 5 5 2
如何编写这样的查询?
感谢您的帮助
答案 0 :(得分:1)
- 查找重复行
SELECT MAX(ID) as ID, CustName, Pincode FROM #Customers
GROUP BY CustName, Pincode
HAVING COUNT(*) > 1
- 删除重复行
DELETE FROM #Customers
WHERE ID IN
( SELECT MAX(ID) FROM #Customers
GROUP BY CustName, Pincode
HAVING COUNT(*) > 1)
取自MSDN。 : http://archive.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=DuplicateRows
如果您无法从该代码中弄明白,请告诉我。
这可能会更接近您的需求。 :
DELETE FROM TABLE
WHERE USERA IN ( SELECT MAX(USERA) FROM TABLE
GROUP BY USERA, USERB, USERBB, USERAA HAVING COUNT(*) > 1)
答案 1 :(得分:0)
下面还介绍了UserA和UserB在两行之间相等但UserAA和UserBB切换相反的情况。你的问题有点不明确究竟是什么构成了重复。希望这至少可以指出你正确的方向。
我首先将它转换为SELECT
语句,并确保它返回您认为应该删除的行,并且仅返回那些行。
DELETE T1
FROM
My_Table T1
INNER JOIN My_Table T2 ON
(
T2.UserA = T1.UserA AND
T2.UserB = T1.UserB AND
T2.UserAA = T1.UserBB AND
T2.UserBB = T1.UserAA AND
T2.UserAA < T2.UserBB
) OR
(
T2.UserA = T1.UserB AND
T2.UserB = T1.UserA AND
T2.UserAA = T1.UserAA AND
T2.UserBB = T1.UserBB AND
T2.UserA < T2.UserB
) OR
(
T2.UserA = T1.UserB AND
T2.UserB = T1.UserA AND
T2.UserAA = T1.UserBB AND
T2.UserBB = T1.UserAA AND
T2.UserA < T2.UserB
)
答案 2 :(得分:0)
只需添加:
UserA&lt;用户B