2016-10-10 205 views
1

我有包含秒[時間]值的數據。我想根據每秒多少條記錄來計數我的數據。組間隔時間間隔爲5秒

這是這樣的:

SELECT [Time], count(*) 

FROM [dbo].[Times] 
GROUP BY 
[Time] ORDER By [Time] 

這給了我:

+----------+----+ 
| 00:00:00 | 4 | 
+----------+----+ 
| 00:00:01 | 2 | 
+----------+----+ 
| 00:00:02 | 1 | 
+----------+----+ 
| 00:00:08 | 2 | 
+----------+----+ 
... 

我想組,並在5秒間隔數得過來,所以結果看起來像:

+----------+----+ 
| 00:00:05 | 7 | <-- # of records between 0:00:00 and 0:00:05 
+----------+----+ 
| 00:00:10 | 2 | <-- # of records between 0:00:05 and 0:00:10 
+----------+----+ 
... 

任何好的方法你在MS SQL中做到這一點?

+0

查看內聯函數以縮短時間。看到這個:http://stackoverflow.com/questions/249794/how-to-round-a-time-in-t-sql – Parfait

+0

'SELECT Cast(Dateadd(SECOND,(Datediff(SECOND,0,[time])/5 + 1)* 5,0)AS TIME)AS [秒], COUNT(*) FROM [DBO]。[次] GROUP BY DATEADD(SECOND,(DATEDIFF(SECOND,0,[時間])/5 + 1)* 5,0); ' –

回答

4

這裏有一個方法:

select cast(dateadd(second, (datediff(second, 0, [time])/5) * 5, 0) as time(0)) as [time], 
     count(*) 
from [dbo].[Times] t 
group by dateadd(second, (datediff(second, 0, [time])/5) * 5, 0) 
order by min([time]); 

編輯:

正如評論指出的那樣,你可以這樣寫:

select v.[Time], count(*) 
from [dbo].[Times] t cross apply 
    (values (cast(dateadd(second, (datediff(second, 0, [time])/5) * 5, 0) as time(0))) 
    ) as v([Time]) 
group by v.[Time] 
order by v.[Time]; 

這使複雜的計算只在一個地方 - - 防止編輯原始答案時出現的錯誤類型。

+0

分組部分看起來效果不錯,但顯示部分不是我的預期。 '1900-01-01 00:00:00.000:7','1900-01-06 00:00:00.000:2' – DDan

+0

您可以在第一列上建議一些格式:00:00:05,00: 00:10 ...? – DDan

+0

您錯誤地放置了'DATEADD'函數中的參數。基於'DATEDIFF'生成結果日期。 'DATEADD'函數應該是'dateadd(second,(datediff(second,0,[time])/ 5 + 1)* 5,0)'。我已經添加了'/ 5 + 1',以'00:00:05'開始結果。' –