SQL 特定时间戳的差异计数

SQL count of differences of specific timestamps

我有一个 table 看起来像这样:

UNIQUEID    FILEKEY DTTMSTAMP
-------------------------------------------
282           1     2012-07-19 09:02:00.000
283           1     2012-07-19 17:12:00.000
284           1     2012-07-20 08:53:00.000
285           1     2012-07-20 17:09:00.000
286           1     2012-07-23 08:54:00.000
287           1     2012-07-23 17:06:00.000
288           1     2012-07-24 09:00:00.000
289           1     2012-07-24 17:04:00.000
290           1     2012-07-25 08:59:00.000
291           1     2012-07-25 17:05:00.000

有超过 50K 行。我需要从中获取以下信息:

我需要计算给定 filekey 恰好有 4 个时间戳的天数,并且第四个 dttmstamp 和第三个 dttmstamp 之间的差异大于 3小时。

最终应该是这样的:

Filekey   Count 
----------------
1         650

等等

SQL 服务器 2012 以后:

with CTE as
(
select FILEKEY, 
       convert(date, DTTMSTAMP) as DTSTAMP,
       DTTMSTAMP, 
       datediff(hh, DTTMSTAMP, lead(DTTMSTAMP) over(partition by FileKey order by DTTMSTAMP)) as Dif,
       row_number() over(partition by FILEKEY order by DTTMSTAMP) as R_ORD
from MyTable
)

select FileKey, count(distinct DTSTAMP)
from CTE
where exists (select 1 from CTE a where a.Filekey = Filekey and Dif >= 3 and R_Ord = 3)
group by FileKey
having max(R_Ord) = 4

在 SQL Server 2012 中,您可以使用 LAG:

;WITH cte AS (
    SELECT  FILEKEY,
            DTTMSTAMP,
            ROW_NUMBER() OVER (PARTITION BY FILEKEY, CAST(DTTMSTAMP as date) ORDER BY DTTMSTAMP) as RN,
            DATEDIFF(second,LAG(DTTMSTAMP,1,NULL) OVER (ORDER BY DTTMSTAMP),DTTMSTAMP)/3600 as SEQ
    FROM YourTable
)

SELECT  FILEKEY,
        COUNT(DTTMSTAMP) as [COUNT]
FROM cte
WHERE RN = 4 and SEQ >= 3
GROUP BY FILEKEY
HAVING MAX(RN) = 4

对于 SQL Server < 2012 这应该适用于 cte 部分:

SELECT  t.FILEKEY,
        t.DTTMSTAMP,
        ROW_NUMBER() OVER (PARTITION BY t.FILEKEY, CAST(t.DTTMSTAMP as date) ORDER BY t.DTTMSTAMP) as RN,
        DATEDIFF(second,DTTMSTAMP_PREV,DTTMSTAMP)/3600 as SEQ
FROM YourTable t
OUTER APPLY (
    SELECT TOP 1 DTTMSTAMP as DTTMSTAMP_PREV
    FROM YourTable
    WHERE FILEKEY = t.FILEKEY AND DTTMSTAMP < t.DTTMSTAMP
    ORDER BY DTTMSTAMP DESC
    ) as d