本文介紹了TSQL 查詢返回相距 5 分鐘之內的所有行的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我想返回表中相距在 5 分鐘內的所有行.
I want to return all the rows in a table that are within 5 mins of each other.
示例表:
KillTime
是我們要查詢的 5 分鐘內
我已經嘗試在 JOINs
和 DATEADD
時間之前做到這一點,但我似乎無法做到這一點.
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 分鐘之內的所有行的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!