我有一个看起来像这样的表:
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
等
答案 0 :(得分:1)
在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
答案 1 :(得分:0)
SQL Server 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