SQL Server 在列中并发 5 个时间戳
Posted
技术标签:
【中文标题】SQL Server 在列中并发 5 个时间戳【英文标题】:SQL Server concurrent 5 timestamps in a columns 【发布时间】:2017-06-11 16:52:12 【问题描述】:我想要一个 SQL 查询,它可以帮助我获取 5 分钟内连续的时间,并且注意到的次数应该大于或等于 5?
例如:
Column A
17:22:23
17:44:31
17:25:36
17:24:11
17:47:39
17:26:22
17:22:44
我的结果应该只获取以下值吗?
17:22:23
17:25:36
17:24:11
17:26:22
17:22:44
【问题讨论】:
什么版本的 SQL Server? 在 SQL Server 2008 之上。SQL Server 2012 对我来说也很好,马丁 那么 2012 年呢?为什么没有显示17:44:31
和 17:47:39
?他们相距不到 5 分钟?
是的,它也应该被获取。做那个例子时没看到。但确切的要求是获取彼此间隔 5 分钟且重复超过 5 次的内容
对不起马丁。之前我的问题不清楚。又改写了一遍。需要在 5 分钟内观察到的时间戳,并且出现次数应大于或等于 5
【参考方案1】:
确切的要求是获取每个之间 5 分钟的东西 其他且重复超过5次
应该这样做
WITH T1
AS (SELECT *,
KeepPreceding = IIF(DATEDIFF(MINUTE, LAG(ColumnA, 4) OVER (ORDER BY ColumnA), ColumnA) <= +5, 1, 0),
KeepFollowing = IIF(DATEDIFF(MINUTE, LEAD(ColumnA, 4) OVER (ORDER BY ColumnA), ColumnA) >= -5, 1, 0)
FROM YourTable),
T2
AS (SELECT *,
/*If at least one of the 4 following rows or this one has the KeepPreceding flag then preserve this row*/
MAX(KeepPreceding) OVER (ORDER BY ColumnA ROWS BETWEEN CURRENT ROW AND 4 FOLLOWING) AS KeptForPreceding,
/*If at least one of the 4 preceding rows or this one has the KeepFollowing flag then preserve this row*/
MAX(KeepFollowing) OVER (ORDER BY ColumnA ROWS BETWEEN 4 PRECEDING AND CURRENT ROW) AS KeptForFollowing
FROM T1)
SELECT ColumnA
FROM T2
WHERE 1 IN ( KeptForPreceding, KeptForFollowing )
ORDER BY ColumnA;
【讨论】:
【参考方案2】:您可以使用lag
和lead
如下:
SELECT [ColumnA]
FROM (SELECT [ColumnA],
PrevVal = LAG([ColumnA]) OVER (ORDER BY [ColumnA]),
NextVal = LEAD([ColumnA]) OVER (ORDER BY [ColumnA])
FROM YourTable) a
WHERE DATEDIFF(MINUTE, PrevVal, [ColumnA]) <= 5
OR DATEDIFF(MINUTE, [ColumnA], NextVal) <= 5;
【讨论】:
谢谢马丁。会尝试并回来。谢谢大家的回复以上是关于SQL Server 在列中并发 5 个时间戳的主要内容,如果未能解决你的问题,请参考以下文章