Need to perform a select which unrolls data

please help, tried different queries with no luck in Oracle environment. To simplify the case, assume that we have one table with records like this

doc_id   doc_date  product_id price
1       01.01.2011    1       20.3
1       01.01.2011    2       10.0
2       15.01.2011    3       10.3
2       15.01.2011    2       null

So, the price for product is set by document from doc_date till next doc_date or to infinity if no more document which sets the new price or reset it to null exists, null means that product sales is not available starting from doc_date.

I need a select which "unrolls" the data in the form:

doc_id   from_date   to_date    product_id price
1        01.01.2011  null          1        20.3
1        01.01.2011  14.01.2011    2        10.0
2        15.01.2011  null          2        null
2        15.01.2011  null          3        10.3

or even:

doc_id   from_date   to_date    product_id price
1        01.01.2011  14.01.2011    1        20.3
1        01.01.2011  14.01.2011    2        10.0
2        15.01.2011  null          2        null
2        15.01.2011  null          3        10.3
any      15.01.2011  null          1        20.3

Thanks!

Upvotes: 2

Views: 66

Answers (1)

Florin Ghita
Florin Ghita

Reputation: 17643

Select 
  doc_id, 
  doc_date as from_date,
  (lead(doc_date) over (partition by product_id order by doc_date) ) - 1  as to_date,
  product_id, 
  price
from
  product_table

Upvotes: 2

Related Questions