SQL 服务器并发 5 个时间戳列
SQL Server concurrent 5 timestamps in a columns
我想得到一个 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
您可以使用 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;
the exact ask is to fetch something that lies 5 mins between each
other and has repeated more than 5 times
应该这样做
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;
我想得到一个 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
您可以使用 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;
the exact ask is to fetch something that lies 5 mins between each other and has repeated more than 5 times
应该这样做
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;