TSQL 查询返回相距 5 分钟之内的所有行

TSQL query to return all rows that are within 5 mins of each other(TSQL 查询返回相距 5 分钟之内的所有行)
本文介绍了TSQL 查询返回相距 5 分钟之内的所有行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想返回表中相距在 5 分钟内的所有行.

I want to return all the rows in a table that are within 5 mins of each other.

示例表:

KillTime 是我们要查询的 5 分钟内

我已经尝试在 JOINsDATEADD 时间之前做到这一点,但我似乎无法做到这一点.

I have tried to do this by JOINs and DATEADD time but i do not seem to be able to quite get there.

推荐答案

DATEADD 是一个选项,但它变得有点复杂.更好的选择是使用 DATEDIFF:

DATEADD is an option, but it gets a little complicated. A better option is to use DATEDIFF:

--Test Setup:
DECLARE @sourceTable AS TABLE (KillID int PRIMARY KEY IDENTITY(1,1), KillTime datetime2(7) NOT NULL);
INSERT INTO @sourceTable (KillTime)
VALUES
    ('2016/02/02 10:01'),
    ('2016/02/02 10:05'),
    ('2016/02/02 10:09'),
    ('2016/02/02 10:30')

--Code:
SELECT *
FROM        @sourceTable AS ST1
INNER JOIN  @sourceTable AS ST2
    ON      ST2.KillID < ST1.KillID                     --Only the smaller IDs so we do not get self joins or duplicates (1 to 2 and 2 to 1).
        AND DATEDIFF(second, ST2.KillTime, ST1.KillTime) BETWEEN -300 AND 300;  --300 seconds is 5 minutes

使用秒而不是分钟来减少舍入/截断问题.

Use seconds instead of minutes to reduce rounding/truncating issues.

这篇关于TSQL 查询返回相距 5 分钟之内的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Query with t(n) and multiple cross joins(使用 t(n) 和多个交叉连接进行查询)
Unpacking a binary string with TSQL(使用 TSQL 解包二进制字符串)
Max rows in SQL table where PK is INT 32 when seed starts at max negative value?(当种子以最大负值开始时,SQL 表中的最大行数其中 PK 为 INT 32?)
Inner Join and Group By in SQL with out an aggregate function.(SQL 中的内部连接和分组依据,没有聚合函数.)
Add a default constraint to an existing field with values(向具有值的现有字段添加默认约束)
SQL remove from running total(SQL 从运行总数中删除)