Oracle SQL:如何显示没有数据的空周/周?

时间:2012-06-28 23:06:26

标签: sql oracle date group-by

this question类似,但我的数据集还有一个包含许多ID的附加列。每个ID都有一个数据集,该数据集可以按照固定的时间范围返回,有些周可能会缺少数据 - 我想填写缺失周数的值。

例如,我想要这个:

ID      WEEKEND_DAY     VALUE
A00     2012-01-01      1
A00     2012-01-08      7
B00     2012-01-08      4
B00     2012-01-15      3

扩展到:

ID      WEEKEND_DAY     VALUE
A00     2012-01-01      1
A00     2012-01-08      7
A00     2012-01-15      0
B00     2012-01-01      0
B00     2012-01-08      4
B00     2012-01-15      3

我已经有一个已知的WEEKEND_DAY范围(在上面的例子中,每周从2012-01-01到2012-01-15),我想填写。我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

使用partitioned outer join

select data.id, weeks.weekend_day, nvl(value, 0) value
from
(
    select date '2012-01-01' weekend_day from dual union all
    select date '2012-01-08' weekend_day from dual union all
    select date '2012-01-15' weekend_day from dual
) weeks
left join
(
    select 'A00' id, date '2012-01-01' weekend_day, 1 value from dual union all
    select 'A00' id, date '2012-01-08' weekend_day, 7 value from dual union all
    select 'B00' id, date '2012-01-08' weekend_day, 4 value from dual union all
    select 'B00' id, date '2012-01-15' weekend_day, 3 value from dual
) data
    partition by (data.id)
    on weeks.weekend_day = data.weekend_day

答案 1 :(得分:0)

假设您每个可能的一周只需要每个ID,这很简单。

首先,如果您还没有“日历表”,我建议您使用。这应该包括一周的“结束”列(或至少是您想要选择的哪一天)。这当然可以通过递归CTE动态生成,但永久性CTE无论如何都是有用的。

鉴于你的原始表:

WITH id_by_date (id, weekend) as (
                 SELECT a.id, b.actualDate
                 FROM (SELECT DISTINCT id
                       FROM original) a  -- or use a table that only has ids
                 CROSS JOIN (SELECT actualDate
                             FROM calendar
                             WHERE isWeekend = '1') b) -- or dayOfWeek = 7
SELECT a.id, a.weekend, COALESCE(b.value, 0)
FROM id_by_date a
LEFT JOIN original b
ON b.id = a.id
AND b.weekend_day = a.weekend
ORDER BY a.id, a.weekend