我的数据包含秒[时间]值。我想根据每秒的记录数计算我的数据。
这样的工作原理如下:
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 :(得分: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];
这使复杂的计算只在一个地方 - 防止我在编辑原始答案时所犯的错误类型。
答案 1 :(得分:0)
如果您尝试使用BigObject数据库,它会提供time_seg()功能来轻松完成此操作。如下所示的查询将返回您想要的结果:
mysql> select time_seg(datetime,5s) as ti, COUNT(*) from t group by ts order by ti;
+---------------------+----------+
| ti | COUNT(*) |
+---------------------+----------+
| 2018-05-09 00:00:00 | 3 |
| 2018-05-09 00:00:05 | 1 |
+---------------------+----------+