您在答案中有一些可行的选项,这里有一个使用 Oracle 的“Windowing Functions with Logical Offset”功能而不是连接或相关子查询的选项。
首先是测试表:
Wrote file afiedt.buf
1 create table t pctfree 0 nologging as
2 select date '2011-09-15' + level / (24 * 4) as date_page_requested
3 from dual
4* connect by level <= (24 * 4)
SQL> /
Table created.
SQL> insert into t values (to_date('2011-09-15 11:11:11', 'YYYY-MM-DD HH24:Mi:SS'));
1 row created.
SQL> commit;
Commit complete.
T 现在在一天中每一刻钟包含一行,并在上午 11:11:11 增加一行。查询分三个步骤进行。第 1 步是,对于每一行,获取在该行时间之后的下一小时内出现的行数:
1 with x as (select date_page_requested
2 , count(*) over (order by date_page_requested
3 range between current row
4 and interval '1' hour following) as hour_count
5 from t)
然后按小时计数分配排序:
6 , y as (select date_page_requested
7 , hour_count
8 , row_number() over (order by hour_count desc, date_page_requested asc) as rn
9 from x)
最后选择后面行数最多的最早行。
10 select to_char(date_page_requested, 'YYYY-MM-DD HH24:Mi:SS')
11 , hour_count
12 from y
13* where rn = 1
如果多个 60 分钟窗口在小时计数中并列,则以上只会给您第一个窗口。