I'm guessing you want a query that splits the rows in groups of consecutive ranges by name? i.e. find if there's any missing rows where the previous end_year <> current start_year?
If so, there's a couple of methods. If the gap between start and end years is always two you could use the Tabibitosan method:
http://rwijk.blogspot.co.uk/2014/01/tabibitosan.html select name, min(start_year) mn, max(end_year) mx from (
select c.*,
start_year - (
row_number() over (partition by name order by start_year) * 2
) rn
from cars c
)
group by name, rn;
NAME MN MX
---------- ---------- ----------
swift 2007 2013
maruti 2009 2011
maruti 2013 2015
For this to work either:
- There must always be 2 years between start and end or
- You can find a function that calculates the different between consecutive rows to 1 (and > 1 if they're not consecutive).
If you can't meet these criteria, you need to check whether the difference between the current start year = previous end. You can do this using lag(). If it is, then assign a group/row number:
case
when lag(end_year, 1, -1) over (partition by name order by end_year) != start_year then
row_number() over (order by end_year)
end rn
You can then "fill down" this value, include it in your group by to get the min/max consecutive years for each make. e.g.:
select name, min(start_year) mn, max(end_year) mx from (
select name, start_year, end_year, rn,
last_value(rn) ignore nulls over (
partition by name order by start_year
) lv
from (
select case
when lag(end_year, 1, -1) over (partition by name order by end_year) != start_year then
row_number() over (order by end_year)
end rn,
c.*
from cars c
)
)
group by name, lv;
NAME MN MX
---------- ---------- ----------
swift 2007 2013
maruti 2009 2011
maruti 2013 2015
Rob also discusses this approach in more detail in the Tabibitosan link above.