I have data like below. In this I need to find rows where the diff in their months should be >= 6. The logic should be, we need to compare from first row until we got the row where diff in months is 6, then need to follow the same logic from the newly matched row and it goes on.
I am adding below my sample data and expected output.
Fromdate LectureiD StudentID Diff Months Expected
1-Oct-13 1102 55586 null
15-Oct-13 1102 55586 0
15-Oct-13 1102 55586 0
4-Apr-14 1102 55586 6
19-Dec-14 1102 55586 8
27-Dec-14 1102 55586 0
14-Jan-15 1102 55586 0
14-Jan-15 1102 55586 0
29-Sep-15 1102 55586 8
1-Oct-13 1102 55557 null
15-Oct-13 1102 55557 0
15-Oct-13 1102 55557 0
4-Apr-14 1102 55557 6
19-Dec-14 1102 55557 8
Below is the logic I tried by using analytical function in oracle.
select lectureid,
studentid,
floor(months_between(fromdate,
lag(fromdate) over (partition by
lectureid,
studentid
order by fromdate
)
)
) monthdiff
from above_table;
Since the lag function will have the default offset of 1 it just checks the row only prior to that because of that the logic I mentioned above is not working properly here since that needs to checked against their prior rows dynamically based on the newly matched row. So the o/p am getting here is as below.
The rows highlighted with asterisk is getting wrong because of this since it compares only with its immediate prior row.
Fromdate LectureiD StudentID Diff Month
1-Oct-13 1102 55586 null
15-Oct-13 1102 55586 0
15-Oct-13 1102 55586 0
*4-Apr-14 1102 55586 5*
19-Dec-14 1102 55586 8
27-Dec-14 1102 55586 0
14-Jan-15 1102 55586 0
14-Jan-15 1102 55586 0
29-Sep-15 1102 55586 8
1-Oct-13 1102 55557 null
15-Oct-13 1102 55557 0
15-Oct-13 1102 55557 0
*4-Apr-14 1102 55557 5*
19-Dec-14 1102 55557 8
Any help here would be greatly appreciated!!!