SQL - 获取在 1 分钟时差内创建的 table 中的所有行

SQL - get all rows in one table created in a time difference of 1 minute

我有一个 table 作为:

   Id  Ticket_NUM        Date                          Comments
   ==  ==========        ========================      =======
   1       2             2014-08-29 08:44:34.122       a
   2       5             2014-08-29 08:44:34.125       b
   3       3             2014-08-29 08:44:34.137       a
   4       4             2016-08-29 08:44:34.137       b

现在,我想获取在同一日期时间 (2014-08-29 08:44:34.122) 上创建的最大时差 < 60 秒的 Ticket_NUM。谁能告诉我如何编写查询来获取这些数据。我在 table 上使用了自连接,但没有得到我正在寻找的 Ticket_NUM(2, 5, 3)。

一种方法是 LEADLAG

select * from(
    select 
       *, 
        myFlag = case 
                    when abs(datediff(second,[date],lag([Date]) over (order by [Date]))) < 60 then 1
                    when abs(datediff(second,[date],lead([Date]) over (order by [Date]))) < 60 then 1
                    else 0
                 end
    from yourtable)
where myFlag = 1
order by [Date]

您可以删除 where myFlag = 1 以查看哪些被标记。

或者更丑陋的方法:

with cte as(
select *, RN = row_number() over (order by [Date])
from yourtable
),

staging as(
    select 
        c.ID
        ,c.Ticket_NUM
        ,c.[Date]
        ,c.Comments
        ,c2DT = min(c2.[Date])
        ,c3DT = max(c3.[Date])
    from 
        cte c
        left join cte c2 on c2.RN = c.RN + 1  --row above
        left join cte c3 on c3.RN = c.RN - 1  --row below
    group by
        c.ID
        ,c.Ticket_NUM
        ,c.[Date]
        ,c.Comments)

select 
    c.ID
    ,c.Ticket_NUM
    ,c.[Date]
    ,c.Comments
from stating c
where abs(datediff(second,c.[Date],c.c2DT)) < 60 or abs(datediff(second,c.[Date],c.c3DT)) < 60