Thursday, 1 November 2018

How To Fetch Anniversary Records for a Selected Record

Hello..!!

Today We will be Discussing about writing SOQL to fetch Anniversary records.

Scenario:

I have an opportunity with some CloseDate (9/3/2015).
Now by writing SOQL, I need to fetch the records of last five years opportunity record where the CloseDate as Same as the selected Opportunity Record (i.e., 9/3)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
Date fromDate = [Select Id, CloseDate from Opportunity WHERE ID = '0066F00000v4dB2'].CloseDate;



integer startYear = fromDate.addYears(-5).year();

integer thisMonth = fromDate.month();

integer thisDay = fromDate.day();

system.debug('*****'+startYear);

system.debug('---'+[Select Id, CloseDate from Opportunity WHERE 

                    CALENDAR_MONTH(CloseDate)=:thisMonth  AND 

                    CALENDAR_YEAR(CloseDate)>=:startYear AND 

                    DAY_IN_MONTH(CloseDate) =: thisDay]);


 This query will return the Following results

No comments:

Post a Comment