填写查询返回值中的空白

时间:2011-11-24 07:42:08

标签: sql oracle

我有一个包含以下列的数据库。

Id    Date              Value
1    12/01/2010 09:30   127.31
1    12/01/2010 09:31   133.41
1    12/01/2010 09:32   147.54
1    12/01/2010 09:34   155.66

基本上,我存储了与时间戳相对应的值。但是,如果值为0,我不存储它(它是一个非常大的数据库,0经常发生,所以我们决定不包括这些行来节省空间)。在上面的示例中,12/01/2010 09:33的值为0,因此未存储。但是,当用户查询数据库时,他会执行类似

的操作
select * from table where Id = '1' and Date > to_date('12/01/2010', 'MM/DD/YYYY')`

我需要填补空白并提及0值的时间戳。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:8)

select 
   nvl(b.id,1) as id, 
   alldates.Date as Date, 
   nvl(b.value,0) as value
from 
  (select level/1440 + to_date('12/01/2010', 'MM/DD/YYYY') as Date
        from dual
        connect by level < 1440 --one day
   ) alldates
  left join
  (select * from table where Id = '1' and Date > to_date('12/01/2010', 'MM/DD/YYYY') b
  on alldates.Date = b.Date

更新(对评论的回应):

select 
   nvl(b.id,1) as id, 
   alldates.Date as Date, 
   nvl(b.value,0) as value,
   nvl(b.value, lag(b.value) over (order by b.Date nulls last)) last_valid_value
from 
  (select level/1440 + to_date('12/01/2010', 'MM/DD/YYYY') as Date
        from dual
        connect by level < 1440 --one day
   ) alldates
  left join
  (select * from table where Id = '1' and Date > to_date('12/01/2010', 'MM/DD/YYYY') b
  on alldates.Date = b.Date