获取 SQL 中时间戳的滚动计数

Get a rolling count of timestamps in SQL

我有一个 table(在 Oracle 数据库中),看起来像下面显示的那样,有大约 4000 条记录。这只是 table 是如何设计的一个例子。时间戳范围为数年。

|        Time                    |    Action      |
|   9/25/2019 4:24:32 PM         |      Yes       |
|   9/25/2019 4:28:56 PM         |      No        |  
|   9/28/2019 7:48:16 PM         |      Yes       |
|         ....                   |     ....       |

我希望能够获得在滚动的 15 分钟间隔内出现的时间戳的计数。我的主要目标是确定在任何 15 分钟间隔内出现的最大时间戳数。我希望通过查看每个时间戳并获取在该时间戳后 15 分钟内出现的时间戳计数来完成此操作。

我的目标是

|      Interval                             |              Count          |
| 9/25/2019 4:24:00 PM - 9/25/2019 4:39:00  |               2             |
| 9/25/2019 4:25:00 PM - 9/25/2019 4:40:00  |               2             |
|            .....                          |             .....           |
| 9/25/2019 4:39:00 PM - 9/25/2019 4:54:00  |               0             |  

我完全不确定我将如何做到这一点。任何想法或建议将不胜感激。

您可以使用递归查询枚举分钟,然后将 table 与 left join:

with recursive cte (start_dt, max_dt) as (
    select trunc(min(time), 'mi'), max(time) from mytable
    union all
    select start_dt + interval '1' minute, max_dt from cte where start_dt < max_dt
)
select 
    c.start_dt,
    c.start_dt + interval '15' minute end_dt,
    count(t.time) cnt
from cte c
left join mytable t 
    on  t.time >= c.start_dt 
    and t.time <  c.start_dt + interval '15' minute
group by c.start_dt

如果你想要数据中的任何 15 分钟间隔,那么你可以使用:

select t.*,
       count(*) over (order by timestamp
                      range between interval '15' minute preceding and current row
                     ) as cnt_15
from t;

如果你想要最大值,那么使用rank()

select t.*
from (select t.*, rank() over (order by cnt_15 desc) as seqnum
      from (select t.*,
                   count(*) over (order by timestamp
                                  range between interval '15' minute preceding and current row
                                 ) as cnt_15
            from t
           ) t
     ) t
where seqnum = 1;

这不会产生您在查询中指定的结果。但它确实回答了这个问题:

I want to be able to get a count of timestamps that occur on a rolling 15 minute interval. My main goal is to identify the maximum number of timestamps that appear for any 15 minute interval.