I’m looking for a query that takes mostly consecutive days and groups them together depending on whether they are really consecutive and on the value belonging to that date. I’m using Oracle version 11g.
This is some example data:
date value
2012-01-01 2000
2012-01-02 2000 //(there is no data for Jan 03 for example)
2012-01-04 2000
2012-01-05 5000
2012-01-06 5000
2012-01-07 5000
2012-01-08 2000
2012-01-09 2000
2012-01-10 2000
(this is the result of quite a large query)
What I’m looking for would group those days together in periods like this:
from_date to_date value
2012-01-01 2012-01-02 2000
2012-01-04 2012-01-04 2000
2012-01-05 2012-01-07 5000
2012-01-08 2012-01-10 2000
We did manage to formulate a query that does what I want, but it’s not a very efficient way, and I’m pretty sure something better/more elegant exists. This is what I’m using now:
with temp_table as (
select a.pk_date DATE1, c.pk_date DATE2, a.volume VOL1
from dm_2203 a, dm_2203 c
where a.volume = c.volume
and a.pk_date <= c.pk_date
and not exists (select 1 from dm_2203 b
where a.volume = b.volume
and a.pk_date = b.pk_date+1)
and not exists (select 1 from dm_2203 d
where c.volume = d.volume
and c.pk_date = d.pk_date-1) )
select * from temp_table y
where date2-date1+1 = (select count(*)
from dm_2203 z
where z.pk_date between y.date1 and y.date2
and y.vol1 = z.volume)
order by 1;
Does anyone have an idea on how to do this faster and without all the joins? Thanks!
I thin this should work and also be reasonable efficient (it should hit the table only once)
Note that if you want to run the logic in an efficient way on a subset of your data, you should add the where clause in the inner most select. Otherwise oracle will have problems to use any index.