我的表格如下所示
ID NAME EMAIL
1 John asd@asd.com
2 Sam asd@asd.com
3 Tom bcd@asd.com
4 Bob bob@asd.com
5 Tom bcd@asd.com
6 Tom bcd@asd.com
7 ash ash@asd.com
8 Bob bob@asd.com
现在我想写一个查询,它应该检测重复的键值对。即如下所示,它应该从SQL表中删除它们。
5 Tom bcd@asd.com
6 Tom bcd@asd.com
8 Bob bob@asd.com
最后,如果我查询我的表,它应该看起来像这样
ID NAME EMAIL
1 John asd@asd.com
2 Sam asd@asd.com
3 Tom bcd@asd.com
4 Bob bob@asd.com
5 ash ash@asd.com
答案 0 :(得分:2)
使用ROW_NUMBER
:
WITH CTE AS(
SELECT [ID], [NAME], [EMAIL],
RN = ROW_NUMBER() OVER (PARTITION BY [NAME], [EMAIL] ORDER BY ID ASC)
FROM dbo.TableName
)
DELETE FROM CTE WHERE RN > 1;
但是你想要的结果不正确。我假设你要删除5并保留7(5是汤姆不灰)。
答案 1 :(得分:0)
这应该适用于MySQL和SQL Server:
delete YourTable
where id not in
(
select min(id)
from YourTable
group by
name
, email
)