如何在一段时间内检查重复数据?

时间:2014-08-21 16:11:53

标签: sql

我们说我有一个带有时间列的表和另一个带有值的列。

我想在一个时间范围内选择具有相同值的任何行,例如在1小时内。我没有选择时间范围来选择,我想在我指定的长度的时间范围内选择行表中的所有数据和重复数据。

1 个答案:

答案 0 :(得分:1)

可能会很慢,但有点像:

 SELECT
     A.ValueColumn,
     A.DateColumn,
     B.DateColumn
 FROM MyTableName AS A
 JOIN MyTableName AS B -- You want two copies of the table so you can find ones with the same value in the timerange
     ON B.ValueColumn = A.ValueColumn -- Obviously you want the value to be the same
 WHERE
     -- You want entries where B is at least as old as A, and at most one hour later
     B.DateColumn BETWEEN A.DateColumn AND DateAdd(Hour, 1, A.DateColumn)
     AND
     B.PrimaryKeyColumn != A.PrimaryKeyColumn -- Just make sure the entries aren't the same element joined onto itself

A是我们的第一个表,B是第二个,这允许我们将表连接到自己来比较条目。我们首先在值上匹配这些表,然后我们过滤条目以确保我们与B比较的条目是在A创建和A创建+ 1小时之间创建的。最后的检查是尝试避免A和B表与自身条目匹配的情况。