按特定间隔过滤行

时间:2014-08-12 06:54:04

标签: sql-server database tsql sql-server-2012

我在表格中有以下DateTime值,只有在此值与>之间存在间隙时才需要过滤该集合。 5秒。这应该是针对特定日期,从第一行开始。

知道如何只在SQL中使用SQL Server 2012吗?

1     2014-04-02 05:33:56.60
2     2014-04-02 05:40:01.55
3     2014-04-02 05:52:45.81
4     2014-04-02 05:52:47.50
5     2014-04-02 06:35:48.84
6     2014-04-02 06:50:49.72
7     2014-04-02 07:01:02.71
8     2014-04-02 07:01:04.35
9     2014-04-02 07:01:09.29
10    2014-04-02 07:44:05.71
11    2014-04-02 08:37:47.06

4 个答案:

答案 0 :(得分:2)

在SQL Server 2012中,您可以使用主导功能,请尝试以下

;with cte as
(
    select id, d,  datediff(s, d, lead(d) over(order by d)) as diff from Test
)
select * from cte where diff > 5

答案 1 :(得分:1)

您可以使用线索功能获取下一个日期和日期值来计算秒差,然后根据您的标准进行过滤。

with cte as
(
    select id, date, diff = datediff(s, date, lead(date) over(order by date)
    from tbl
)
select * from cte where diff > 5

答案 2 :(得分:1)

你可以像这样使用它

WITH    rows AS
    (
    SELECT  *, ROW_NUMBER() OVER (ORDER BY InputDate) AS rn
    FROM    given_table
    )
SELECT  DATEDIFF(second, mc.InputDate, mp.InputDate)
FROM    rows mc
JOIN    rows mp
ON      mc.rn = mp.rn - 1
where DATEDIFF(second, mc.InputDate, mp.InputDate)> 5

答案 3 :(得分:0)

希望这也会对你有所帮助。

DECLARE @TAB TABLE (ID INT,DT DATETIME)
INSERT INTO @TAB VALUES
(1 ,'2014-04-02 05:33:56.60'),
(2 ,'2014-04-02 05:40:01.55'),
(3 ,'2014-04-02 05:52:45.81'),
(4 ,'2014-04-02 05:52:47.50'),
(5 ,'2014-04-02 06:35:48.84'),
(6 ,'2014-04-02 06:50:49.72'),
(7 ,'2014-04-02 07:01:02.71'),
(8 ,'2014-04-02 07:01:04.35'),
(9 ,'2014-04-02 07:01:09.29'),
(10,'2014-04-02 07:44:05.71'),
(11,'2014-04-02 08:37:47.06')

- 查询

SELECT  A.*,B.* 
FROM    @TAB A,@TAB B 
WHERE   A.ID = B.ID - 1
AND     DATEDIFF(SECOND,A.DT,B.DT) > 5

- 结果

enter image description here