Oracle组按时间段限定行,包括零计数

时间:2014-05-12 04:38:29

标签: sql oracle window-functions

假设我有一个Oracle 10g表,它记录了我系统上的所有响应时间。如何按日期获得计数缓慢的交易,包括没有交易缓慢的日期的零计数?

作为一个例子

create table response_times (system_datetime timestamp, server_name varchar2(3), response_time number(9));

insert into response_times (system_datetime, server_name, response_time)
values (to_date('01/05/2014 12:30', 'DD/MM/YYYY HH24:MI'), 'D01', 500);

insert into response_times (system_datetime, server_name, response_time)
values (to_date('01/05/2014 13:45', 'DD/MM/YYYY HH24:MI'), 'D02', 700);

insert into response_times (system_datetime, server_name, response_time)
values (to_date('01/05/2014 14:01', 'DD/MM/YYYY HH24:MI'), 'D01', 2500);

insert into response_times (system_datetime, server_name, response_time)
values (to_date('02/05/2014 07:45', 'DD/MM/YYYY HH24:MI'), 'D02', 2500);

insert into response_times (system_datetime, server_name, response_time)
values (to_date('02/05/2014 08:30', 'DD/MM/YYYY HH24:MI'), 'D02', 500);

我希望看到响应时间超过2000毫秒的事务数量,如下所示:

TRUNC(system_datetime)  D01    D02
=====================   ===    ===
2014/05/01              1      0
2014/05/02              0      1
2014/05/03              0      0

有没有办法在单个sql语句中检索它?在实践中,将有数百万行,(希望)每天只有几个慢速交易,并且在某些日子里根本不会有缓慢的交易。

现在我知道我可以编写一个简短的PL / SQL过程来使用候选日期的临时表来获取它,并且循环为每个时间段发出一个选择计数(*)以获得计数值,但是我希望有更优雅的方式...

1 个答案:

答案 0 :(得分:2)

关键是生成日期。这是一种方法:

with n as (
      select level as lvl from dual
      connect by level < 5
     ),
     dates as (
      select (to_date('2014-05-01', 'YYYY-MM-DD') + lvl - 1) as d
      from n
     )
select dates.d, coalesce(r.D01, 0) as D01, coalesce(r.D02, 0) as D02
from dates left outer join
     (select TRUNC(system_datetime) as dt,
             sum(case when server_name = 'D01' then 1 else 0 end) as D01,
             sum(case when server_name = 'D02' then 1 else 0 end) as D02
      from response_times
      group by TRUNC(system_datetime) 
     ) r
     on dates.d = r.dt;

获得日期后,剩下的只是left outer join