我将展示我如何使用 Oracle 实现这一目标,然后如何将其应用于 Vertica。
我首先编写一个查询来获取日期列表。像这样:
select to_date('01-APR-2015','dd-mon-yyyy') + rownum -1 as begin_date
from all_objects
where rownum <= to_date('05-APR-2015','dd-mon-yyyy') - to_date('01-APR-2015','dd-mon-yyyy')+1;
这将返回:
01-APR-15 12:00:00 AM
02-APR-15 12:00:00 AM
03-APR-15 12:00:00 AM
04-APR-15 12:00:00 AM
05-APR-15 12:00:00 AM
我对 Vertica 不太熟悉,但看起来可以通过以下查询来实现:
SELECT ts::DATE
FROM (SELECT '04/01/2015'::TIMESTAMP as tm
UNION
SELECT '04/05/2015'::TIMESTAMP as tm) as t
TIMESERIES ts as '1 Day' OVER (ORDER BY tm);
(来源:http ://www.vertica-forums.com/viewtopic.php?t=1333 )
然后我使用笛卡尔/交叉连接到相同的查询来创建日期范围:
select *
from (
select to_date('01-APR-2015','dd-mon-yyyy') + rownum -1 as begin_date
from all_objects
where rownum <= to_date('05-APR-2015','dd-mon-yyyy')-to_date('01-APR-2015','dd-mon-yyyy')+1
) q1, (
select to_date('01-APR-2015','dd-mon-yyyy') + rownum -1 as end_date
from all_objects
where rownum <= to_date('05-APR-2015','dd-mon-yyyy')-to_date('01-APR-2015','dd-mon-yyyy')+1
) q2
where begin_date <= end_date;
结果如下所示:
BEGIN_DATE END_DATE
01-APR-15 12:00:00 AM 01-APR-15 12:00:00 AM
01-APR-15 12:00:00 AM 02-APR-15 12:00:00 AM
01-APR-15 12:00:00 AM 03-APR-15 12:00:00 AM
01-APR-15 12:00:00 AM 04-APR-15 12:00:00 AM
01-APR-15 12:00:00 AM 05-APR-15 12:00:00 AM
02-APR-15 12:00:00 AM 02-APR-15 12:00:00 AM
02-APR-15 12:00:00 AM 03-APR-15 12:00:00 AM
02-APR-15 12:00:00 AM 04-APR-15 12:00:00 AM
02-APR-15 12:00:00 AM 05-APR-15 12:00:00 AM
03-APR-15 12:00:00 AM 03-APR-15 12:00:00 AM
03-APR-15 12:00:00 AM 04-APR-15 12:00:00 AM
03-APR-15 12:00:00 AM 05-APR-15 12:00:00 AM
04-APR-15 12:00:00 AM 04-APR-15 12:00:00 AM
04-APR-15 12:00:00 AM 05-APR-15 12:00:00 AM
05-APR-15 12:00:00 AM 05-APR-15 12:00:00 AM
如果您不想要单日范围(例如,2015 年 4 月 1 日 - 2015 年 4 月 1 日),只需将 begin_date <= end_date 更改为 begin_date < end_date。
一旦你有了它,你可以将整个查询加入到你正在运行的查询中:
Select q.begin_date, q.end_date, t.B, t.C, t.D, count(t.A)
FROM tmp t, (
select *
from (
select to_date('01-APR-2015','dd-mon-yyyy') + rownum -1 as begin_date
from all_objects
where rownum <= to_date('05-APR-2015','dd-mon-yyyy')-to_date('01-APR-2015','dd-mon-yyyy')+1
) q1, (
select to_date('01-APR-2015','dd-mon-yyyy') + rownum -1 as end_date
from all_objects
where rownum <= to_date('05-APR-2015','dd-mon-yyyy')-to_date('01-APR-2015','dd-mon-yyyy')+1
) q2
where begin_date <= end_date
) q
where t.theDate between q.begin_date and q.end_date
group by q.begin_date, q.end_date, t.B, t.C, t.D
order by q.begin_date, q.end_date;
这是一个 SQLFiddle:http ://sqlfiddle.com/#!4/9628d/9
我希望这会有所帮助。