如何使用基于时间的滑动窗口计算行数?

时间:2015-11-20 05:10:02

标签: sql sql-server

我有以下简单的schema

CREATE TABLE Data (ts DATETIME)
INSERT INTO Data VALUES
('2015-11-11 06:20:41.937'),
('2015-11-11 06:20:42.017'),
('2015-11-11 06:20:42.060'),
('2015-11-11 06:20:44.837'),
('2015-11-11 06:20:44.853'),
('2015-11-11 06:20:45.640'),
('2015-11-11 06:20:46.197'),
('2015-11-11 06:20:46.233'),
('2015-11-11 06:21:59.613'),
('2015-11-11 06:21:59.613'),
('2015-11-11 06:22:17.377'),
('2015-11-11 06:23:40.187'),
('2015-11-11 06:24:40.227'),
('2015-11-11 06:24:40.227')

实际上,当然还有更多的专栏。

无论如何,我试图找出如何计算每行从该行开始的10秒间隔内的行数。对于示例数据,结果应为:

ts                      Count
2015-11-11 06:20:41.937 8
2015-11-11 06:20:42.017 7
2015-11-11 06:20:42.060 6
2015-11-11 06:20:44.837 5
2015-11-11 06:20:44.853 4
2015-11-11 06:20:45.640 3
2015-11-11 06:20:46.197 2
2015-11-11 06:20:46.233 1
2015-11-11 06:21:59.613 2
2015-11-11 06:21:59.613 2
2015-11-11 06:22:17.377 1
2015-11-11 06:23:40.187 3
2015-11-11 06:24:40.227 2
2015-11-11 06:24:40.227 2

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

试试这个

select d.ts, (select count(*) cnt
              from data d2
              where d2.ts>=d.ts
                    and d2.ts<dateadd(second,10,d.ts)) cnt
from data d

答案 1 :(得分:1)

您可以使用CROSS APPLY

SELECT
    ts, cnt
FROM Data d
CROSS APPLY(
    SELECT COUNT(*)
    FROM Data
    WHERE ts BETWEEN d.ts AND DATEADD(SECOND, 10, d.ts)
) AS x(cnt)
ORDER BY d.ts