我想从表中删除重复(与值相同且相同)元组,但需要保持元组的最小对象ID(对象ID为pk)。
所以这是列:
来自|到|时间|距离| object_id
我可以看到通过执行
删除的正确元组数select [from],[to],count(*)
FROM table
where [object_id] NOT IN(
SELECT min([object_id])
FROM table
group by [from],[to]
having count(*) > 1)
group by [from],[to]
having count(*) > 1
但是我想首先看到在上面的SQL上计算的object_id。
答案 0 :(得分:1)
您可以尝试使用此功能(未经测试)......
;WITH temp AS (
SELECT [from_id], [to_id], [object_id] = min([object_id])
FROM table
group by [from_id],[to_id]
having count(*) > 1)
SELECT
t2.[from_id],
t2.[to_id],
t.[object_id]
FROM
table t
join temp t2
on t2.[from_id] = t.[from_id]
AND t2.[to_id] = t.[to_id]
AND t2.[object_id] != t.[object_id]
编辑:
CTE temp将使用min object_id产生所有不同的分组,你想要保留一个。
SELECT [from_id], [to_id], [object_id] = min([object_id])
FROM table
group by [from_id],[to_id]
having count(*) > 1
您还想删除其他对,这些对是来自/对,但具有不同的object_id。最后一个选择应该准确输出那些记录。