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 分钟之内的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)