从小于指定分钟数的行中选择非重复值

时间:2010-10-22 00:16:55

标签: sql sql-server sql-server-2005 tsql

我有一个大表格,格式如下:

DATETIME                   NUMBER
--------------------------------------
2009-03-31 16:05:52.000    2453651622
2009-03-31 16:16:12.000    30206080
2009-03-31 16:16:16.000    16890039
2009-03-31 16:16:28.000    2452039696
2009-03-31 16:16:33.000    140851934
2009-03-31 16:16:51.000    2453120306
2009-03-31 16:16:57.000    2453120306
...
2009-04-01 21:15:24.000    2453651622

如果第二列中的行数间隔不到15分钟,如何选择没有重复数字的行?

在前面的示例中,编号为2453120306的第二行是重复的,因为它与前一行相距不到15分钟,因此不应选择。

最后一行与第一行的编号相同,但它不是重复的,因为它在24小时后发生的更多。

2 个答案:

答案 0 :(得分:1)

-- distinct required in case there are rows with 
-- exactly the same values for datetime and number
SELECT DISTINCT a.*
FROM your_table AS a
    LEFT JOIN your_table AS b
        ON a.[number] = b.[number]
            AND a.[datetime] > b.[datetime]
            AND a.[datetime] <= DATEADD(minute, 15, b.[datetime])
WHERE b.Number IS NULL

答案 1 :(得分:0)

试试这个:

Select * From Table t
Where Not Exists
   (Select * From Table
    Where DateTime Between DateAdd(second, -450,  t.DateTime)
                       And DateAdd(second,  450,  t.DateTime)
        -- next row is better to exclude same row using a PK if available
        And DateTime <> t.DateTime 
        And Number = t.Number) 

根据您的回答编辑也使用滑动15分钟。