如何在SQL Server表中找到重复值?

时间:2015-01-27 10:35:07

标签: sql-server-2008 tsql

我的SQL Server 2008数据库有一个名为Reading的表,其中Timestamp列为DateTime值,Probe_idProbe表的外键列。

遗憾的是,我的数据库在我希望删除的Reading表格中有一些重复的值,但我正在努力查询它们。

我认为这样的东西会找到重复的东西:

select * from Reading where Probe_id = Probe_id and Timestamp = Timestamp;

有人有什么想法吗?

2 个答案:

答案 0 :(得分:2)

按列进行分组,使记录重复,然后计算每个组的数量

select Probe_id, Timestamp, count(*) as num_of_duplicates
from Reading 
group by Probe_id, Timestamp
having count(*) > 1

答案 1 :(得分:2)

WITH    Duplicates
      AS (SELECT    Probe_id,
                    Timestamp,
                    ROW_NUMBER() OVER (PARTITION BY Probe_id, Timestamp ORDER BY Probe_id, Timestamp) AS [RowNumber]
          FROM      Reading
         )
DELETE  FROM Duplicates
WHERE   Duplicates.RowNumber > 1