Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find month gaps in Oracle table?

I have a Oracle table which has EmpName (Char),Month_from and Month_to column (Numeric). Here I need to find missing months ( Month gaps). In the below sample data I have to find missing month 6 (Jun ).

Thanks in advance.

Sample Data:

|-------|-----------|--------|
|eName  |Month_From |Month_To|
|(Char) | ( Int)    | ( Int) |
|-------|------------|-------|
|John   |1          |2       | ( Jan to Feb)
|John   |3          |5       | ( Mar to May)
|John   |7          |8       | ( Jul to Aug)    
|-------|------------|-------|

Need to Find (Jun to Jun).

like image 572
Jegan Avatar asked Nov 17 '25 22:11

Jegan


1 Answers

Assuming no overlaps, you can find the missing months using lag():

select (prev_month_to + 1) as start_missing,
       (month_from - 1) as end_missing
from (select t.*, lag(month_to) over (partition by name order by month_from) as prev_month_to
      from t
     ) t
where prev_month_to <> month_from - 1;

This provides a range for each gap, because the gap could be more than one month.

like image 89
Gordon Linoff Avatar answered Nov 19 '25 13:11

Gordon Linoff