Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling gaps in query return value

Tags:

sql

oracle

I have a database that has columns as follows.

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

Essentially, I store values corresponding to timestamps. However, if a value is 0, I dont store it(Its a really large database, and 0's occur frequently, so we decided to not include those rows to save space). In the above example, 12/01/2010 09:33 has a 0 value so its not stored. However when a user queries the database, he does something like

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

and I need to fill in the gaps and mention timestamps with 0 values. How can I do this?

like image 407
Aks Avatar asked Nov 24 '11 07:11

Aks


1 Answers

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

UPDATED(response to comment):

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
like image 70
Florin stands with Ukraine Avatar answered Nov 11 '22 10:11

Florin stands with Ukraine