使用 8i 使得这比在以后的版本中要复杂一些。
您可以使用分层查询从最早的日期和月数开始生成现有数据所涵盖范围内的所有月份的列表:
select item, min(period_start_date) min_date,
months_between(max(period_start_date), min(period_start_date)) as num_months
from your_table
group by item
...并将其用作分层查询的内部查询:
select item, add_months(min_date, level) as period_start_date
from (
select item, min(period_start_date) min_date,
months_between(max(period_start_date), min(period_start_date)) as num_months
from your_table
group by item
)
connect by level < num_months
在这种情况下,这为您提供了 4 至 8 月的六个虚拟行。(我们知道我们不需要 3 月或 9 月的虚拟行)。
然后,您可以使用 ; 排除具有同一日期真实数据的任何数据not exists
;并将其与真实表中的数据结合起来:
select item, period_start_date, qty_used
from your_table
union all
select item, period_start_date, 0
from (
select item, add_months(min_date, level) as period_start_date
from (
select item, min(period_start_date) min_date,
months_between(max(period_start_date), min(period_start_date)) as num_months
from your_table
group by item
)
connect by level < num_months
) t
where not exists (
select null
from your_table
where item = t.item
and period_start_date = t.period_start_date
)
order by item, period_start_date;
ITEM PERIOD_STAR QTY_USED
---------- ----------- ----------
1234 01-MAR-2015 10
1234 01-APR-2015 0
1234 01-MAY-2015 0
1234 01-JUN-2015 32
1234 01-JUL-2015 14
1234 01-AUG-2015 0
1234 01-SEP-2015 11
使用固定的开始日期,您可以修改生成的表:
select item, period_start_date, qty_used
from your_table
union all
select item, period_start_date, 0
from (
select item, add_months(date '2013-03-01', level - 1) as period_start_date
from (select distinct item from your_table)
connect by add_months(date '2013-03-01', level - 1) < sysdate
) t
where not exists (
select null
from your_table
where item = t.item
and period_start_date = t.period_start_date
)
order by item, period_start_date;
您也可以从生成的表数据中进行左外连接,但当然必须使用旧的 Oracle 特定语法:
select t.item, t.period_start_date, nvl(yt.qty_used, 0) as qty
from (
select item, add_months(date '2013-03-01', level - 1) as period_start_date
from (select distinct item from your_table)
connect by add_months(date '2013-03-01', level - 1) < sysdate
) t, your_table yt
where yt.item (+) = t.item
and yt.period_start_date (+) = t.period_start_date
order by t.item, t.period_start_date;