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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With