从Oracle中选择没有数据日期的空日期?

时间:2010-11-23 19:13:30

标签: sql oracle join union

我有第二个存储的一系列指标。我正在尝试制作一份能够完成以下任务的报告:

  • avg metric by hour
  • 每小时最高
  • 每小时
  • 包括小时的日期/时间 没有数据

此查询几乎产生正确的结果。但是,有几天有数据,我不希望UNION结果产生空值。我想让那些人放弃。

SELECT HOUR, METRIC, MINIMUM, MAXIMUM FROM (
select
  to_char(day,'DD-MON-YY "-" HH24":00"') AS HOUR,
  round(avg(duration), 2) AS METRIC,
  round(min(duration), 2) AS MINIMUM,
  round(max(duration), 2) AS MAXIMUM
from log_events
where day > to_date('08-NOV-10', 'DD-MON-YY')
  and day < to_date('08-NOV-10', 'DD-MON-YY') + 2
  and company = 'company A'
  and component = 'api layer'
  and event_label = 'execution request'
  group by to_char(day,'DD-MON-YY "-" HH24":00"')
  UNION
  select to_char(trunc(to_date('08-NOV-10', 'DD-MON-YY'))+(level-1)/24, 'DD-MON-YY "-" HH24":00"') HOUR,
     null as METRIC,
     null as MINIMUM,
     null as MAXIMUM
  from dual connect by level <= 48
)
order by HOUR;

我甚至不确定这是否是查询数据的正确方法。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

使用小时创建一个内联表,然后将其连接到log_events表:

select
  dummy_hours.hour,
  log_aggregate.METRIC,
  log_aggregate.MINIMUM,
  log_aggregate.MAXIMUM
from (
  select to_char(trunc(to_date('08-NOV-10', 'DD-MON-YY'))+(level-1)/24, 'DD-MON-YY "-" HH24":00"') HOUR
  from dual connect by level <= 48
) dummy_hours, (
  select to_char(day,'DD-MON-YY "-" HH24":00"') AS HOUR,
  round(avg(duration), 2) AS METRIC,
  round(min(duration), 2) AS MINIMUM,
  round(max(duration), 2) AS MAXIMUM
  from log_events
  where day between to_date('08-NOV-10', 'DD-MON-YY') and to_date('08-NOV-10', 'DD-MON-YY') + 2
  and day > to_date('08-NOV-10', 'DD-MON-YY')
  and day < to_date('08-NOV-10', 'DD-MON-YY') + 2
  and company = 'company A'
  and component = 'api layer'
  and event_label = 'execution request'
  group by to_char(day,'DD-MON-YY "-" HH24":00"')
) log_aggregate
where dummy_hours.hour = log_aggregate.hour(+)
order by dummy_hours.hour;