0

我想从表中删除重复的(与值相同且与值相同)元组,但需要保留具有最小对象 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。

4

1 回答 1

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 的不同 from/to 分组,您想保留一个。

SELECT [from_id], [to_id], [object_id] = min([object_id])
FROM table
group by [from_id],[to_id]
having count(*) > 1

您还想删除其他对,这些对是相同的 from/to 对,但具有不同的 object_id。最后一次选择应该准确地输出这些记录。

于 2013-06-14T12:52:52.893 回答