You may want to check the max(year) part . for situation like this i try to number the month in ascending order . for example lest's say i hav date from dec 2017 till today , so i will assign 1 to dec 207, to jan 2018 and so on . It will help when calculating previous month as well.