I am trying to create a function in MySQL where it takes a value of MaxDate (as '2020-09-01') and depending on the value of other date (input), it returns different GroupNum as a final outcome.
I am stuck where I used both 'While End' and 'If Then' condition, and it does not add up the value and return the result as I expected, but it keeps looping.
So, I have example both for 1st 12 month (Oct 2019-Sep 2020) and then for the rest where I am trying to use While Loop to add values dynamically.
I put the max GroupNumber range as '6' but I was not sure how to control that value dynamically either.
-- Reference:
-- 2019-09-01 >= date_sub(2020-09-01, interval (12*1) + 11) month) and 2020-09-01 <=
-- date_sub(2020-09-01, interval (12*1) month
-- 2018-09-01 >= date_sub(2020-09-01, interval (12*2) + 11) month) and 2020-09-01 <=
-- date_sub(2020-09-01, interval (12*2) month ..etc...
DECLARE GroupNumAdd INT default 1;
DECLARE GroupNum INT default 1;
DECLARE MonthVar int default 12;
DECLARE Var INT default 11;
DECLARE MaxDate date;
select fn_MaxDate() into MaxDate;
-- MaxDate is '2020-09-01'
-- for date range of 2019-10-01 to 2020-09-01:
IF YYMMDD >= date_sub(MaxDate, interval Var month) then
set GroupNum = 1;
end If;
-- for rest of date range (any date before 2019-10-01):
while GroupNum <= 6 DO
IF YYMMDD >= date_sub(MaxDate, interval (MonthVar*GroupNumAdd + Var) month) and MonthDesc <= date_sub(MaxDate, interval (MonthVar*GroupNumAdd) month) then
set GroupNum = GroupNum + 1;
set GroupNumAdd = GroupNumAdd + 1;
end if;
end while;
RETURN GroupNum;
END
Aucun commentaire:
Enregistrer un commentaire