我會告訴我如何與甲骨文實現這一目標以及如何同可能適用於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)
然後,我使用笛卡爾/交叉連接到相同的查詢來創建日期運行GES:
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 to 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
我希望幫助。
哪個RDBMS是爲了這個?請添加一個標籤來指定您是使用'mysql','postgresql','sql-server','oracle'還是'db2' - 或者其他的東西。 –