declare @ownerId int = ; declare @ownertype varchar(3) = ; with data as ( select e.eventId, cast( floor( 10191817 * sqrt( e.eventId * log10( e.eventId ))) as bigint ) as eventIdTk, e.eventName, convert( varchar, min( sDay.eventDate ), 101 ) as startDate, convert( varchar, max( eDay.eventDate ), 101 ) as endDate, e.partnerId, e.partnerType, e.ccLocalManager, e.ccDivisionManager, e.createDate, e.comments emailRecipients, e.surveryId from tbl_EVT_Events e with (nolock) inner join tbl_EVT_EventDates sDay with (nolock) on e.eventid = sDay.eventId inner join tbl_EVT_EventDates eDay with (nolock) on e.eventid = eDay.eventId where e.ownerType = @ownerType and e.ownerId = @ownerId and e.eventTypeId = 2 and e.partnerType = 'CDR' and #applyFilter( attributes.datastore.filter )# group by e.eventId, e.eventName, e.partnerId, e.partnerType, e.ccLocalManager, e.ccDivisionManager, e.createDate, e.comments ) #forJSON( 'data', attributes.datastore, _defaultSortField )#