在MS SQL中按ID和时间间隔分组

时间:2019-06-15 00:04:17

标签: sql sql-server tsql

我正在尝试编写一个在一段时间内将ID分组的查询。

现实世界场景: 我想在5秒内看到由同一ID创建的行。

SELECT top 10 
Id, 
CreatedOn
FROM Logs
where ((DATEPART(SECOND, CreatedOn) + 5) - DATEPART(SECOND, CreatedOn)) < 10
GROUP BY 
DATEPART(SECOND, CreatedOn),
Id,
CreatedOn
order by CreatedOn desc

这不是很正确,但是我感觉自己走在正确的轨道上。

预先感谢

2 个答案:

答案 0 :(得分:1)

您可以尝试在ID匹配的情况下进行查询,并且自纪元以来的秒数在匹配记录的5秒钟之内:

SELECT
    t1.Id,
    t1.CreatedOn
FROM logs t1
WHERE EXISTS (SELECT 1 FROM logs t2
              WHERE t1.Id = t2.Id AND
                    t1.CreatedOn <> t2.CreatedOn AND
                    ABS(DATEDIFF(SECOND, t1.CreatedOn, t2.CreatedOn)) <= 5)
ORDER BY
    t1.CreatedOn DESC;

答案 1 :(得分:0)

可以通过以下方式进一步优化:

SELECT t1.Id,
       ,t1.CreatedOn
FROM   logs t1
WHERE  EXISTS (
               SELECT 1 
               FROM   logs t2
               WHERE  t2.Id = t1.Id
               AND    t2.CreatedOn <> t1.CreatedOn 
               AND    ABS(DATEDIFF(SECOND, t1.CreatedOn, t2.CreatedOn)) <= 5
              )
ORDER  BY
       t1.CreatedOn DESC;