2012-11-02 150 views
0

我有一個包含以下列的超過100,000行的表:ID,時間和布爾值。
時間列追蹤時間到第二個。
我需要一個查詢,從表的開始到結束每隔5分鐘的時間間隔查找所有Boolean = 1的實例,然後按時間間隔對計數進行分組。在SQL中以5分鐘的時間間隔查找記錄

該表代表4小時的數據,所以我應該得到48行結果。
我正在使用MS SQL Server。

我已經嘗試了幾種方法,但時間間隔邏輯給我一個很難。

編輯:我想通了!

SELECT DATEADD(MINUTE, DATEDIFF(MINUTE, 0, timestamp)/5 * 5,0), COUNT(*) 
FROM table 
WHERE isrepeat = 1 
GROUP BY by DATEADD(MINUTE, DATEDIFF(MINUTE, 0, timestamp)/5 * 5,0) 
ORDER BY by 1 
+1

看看這個SO線程。 http://stackoverflow.com/questions/7992252/group-by-time-interval – Htaras

回答

2

這應該做。您可以按照時間間隔/ 5對您的結果進行分組。

select 
cast(to_char(Time, 'mi') as int)/5 * 5 || ' - ' || cast(to_char(Time, 'mi') as int)/5 * 5 + 5 as "Interval", 
count(1) 
from tableName 
where 
Boolean = 1 
group by 
cast(to_char(Time, 'mi') as int)/5 
+0

這將是一個有效的答案** ORACLE ** – RichardTheKiwi

1
select * from tableName where Time 
BETWEEN DATEADD(minute, -5, current_timestamp) 
AND current_timestamp 
相關問題