2016-05-18 185 views
1

如何從SQL表中獲取最後5分鐘的記錄。如何從SQL數據庫表中獲取最後5分鐘的記錄?

例如:我有一個名爲Student的表名。

ID Name  StartTime 
-- ---------- ---------------------- 
1 abc   2016-05-18 08:00:29.587 
2 xxx   2016-05-18 08:05:30.287 
3 xyz   2016-05-18 08:10:30.287 

現在考慮的時間是上午8:15。我想從"Student"表中獲取最後5分鐘記錄。

例如: 我需要「xyz」用戶信息。

我試過下面的查詢不工作。

select * from Student where startTime is not null and startTime < GetDate() and startTime > dateadd(minute, -5, GetDate()) 

但我從學生表中獲得空值。

如何做到這一點。請幫我解決。

+0

基於根據你的解釋,沒有理由你沒有記錄。 StartTime是什麼數據類型?如果你運行'select dateadd(minute,-5,GetDate()),getdate()' –

回答

0
select * from Student where startTime is not null and startTime > DATEADD(minute, -5, GETUTCDATE()) 

試試這個代碼

2

這可能是由於日期時間的秒部分。你想要做的是確保你從日期時間刪除seconds。這裏是如何:

SELECT CAST(CONVERT(VARCHAR(16), GETDATE(), 120) + ':00' AS DATETIME) 

然後在比較使用的結果,就像這樣:

CREATE TABLE Student(
    ID  INT, 
    Name VARCHAR(3), 
    StartTime DATETIME 
); 
INSERT INTO Student VALUES 
(1, 'abc', '2016-05-18 08:00:29.587 '), 
(2, 'xxx', '2016-05-18 08:05:30.587 '), 
(3, 'xyz', '2016-05-18 08:10:30.587 '); 

DECLARE @currDate DATETIME = '2016-05-18 08:15:59.000' 

SELECT @currDate = CAST(CONVERT(VARCHAR(16), @currDate, 120) + ':00' AS DATETIME) 

SELECT * 
FROM Student 
WHERE startTime > DATEADD(MINUTE, -5, @currDate) 


DROP TABLE Student; 

結果:

ID   Name StartTime 
----------- ---- ----------------------- 
3   xyz 2016-05-18 08:10:30.587 
+0

,那麼會發生什麼......感謝所有....工作正常 – dhamo

2

試試這個,

SELECT * 
FROM Student 
WHERE STARTIME >= Dateadd(MINUTE, -5, GETDATE()) 
相關問題