这里的技巧是生成所有间隔的列表,然后对表进行外部连接以查看每个间隔中有多少条记录。
假设您有一个查询范围(这里我设置了varchar2
绑定变量,以便我可以在 SQL*Plus 中轻松运行它,您可以从您的 Web 客户端执行其他操作,例如?
JDBC),您可以执行类似的操作:
var start_time varchar2(16);
var end_time varchar2(16);
exec :start_time := '12/07/2012 08:00:00';
exec :end_time := '12/07/2012 12:00:00';
select start_time + (level - 1)/48 as period_start,
start_time + level/48 - interval '1' second as period_end
from (
select to_date(:start_time, 'DD/MM/YYYY HH24:MI:SS') start_time,
to_date(:end_time, 'DD/MM/YYYY HH24:MI:SS') end_time
from dual
)
connect by start_time + (level - 1)/48 < end_time;
它会生成 08:00 到 12:00 之间所有半小时时段的列表:
PERIOD_START PERIOD_END
------------------- -------------------
12/07/2012 08:00:00 12/07/2012 08:29:59
12/07/2012 08:30:00 12/07/2012 08:59:59
12/07/2012 09:00:00 12/07/2012 09:29:59
12/07/2012 09:30:00 12/07/2012 09:59:59
12/07/2012 10:00:00 12/07/2012 10:29:59
12/07/2012 10:30:00 12/07/2012 10:59:59
12/07/2012 11:00:00 12/07/2012 11:29:59
12/07/2012 11:30:00 12/07/2012 11:59:59
然后您可以将其用作 CTE 或子查询并在您的真实表中查找匹配的记录:
with tmp_tab as (
select start_time + (level - 1)/48 as period_start,
start_time + level/48 - interval '1' second as period_end
from (
select to_date(:start_time, 'DD/MM/YYYY HH24:MI:SS') start_time,
to_date(:end_time, 'DD/MM/YYYY HH24:MI:SS') end_time
from dual
)
connect by start_time + (level - 1)/48 < end_time
)
select to_char(tt.period_start, 'DD/MM/YYYY HH24:MI') dt,
count(ts.track_datetime)
from tmp_tab tt
left join tbl_stat ts
on ts.track_datetime between tt.period_start and tt.period_end
group by tt.period_start
order by tt.period_start;
使用只有几条记录的虚拟表,这给出:
DT COUNT(TS.TRACK_DATETIME)
---------------- ------------------------
12/07/2012 08:00 0
12/07/2012 08:30 0
12/07/2012 09:00 1
12/07/2012 09:30 2
12/07/2012 10:00 0
12/07/2012 10:30 1
12/07/2012 11:00 0
12/07/2012 11:30 0