where 1 = 1 and #applyFilter( attributes.datastore.filter )# order by eventDay ---> declare @ownerId int = ; declare @ownertype varchar(3) = ; with getData as ( select e.eventId, e.eventName, e.ownerid, e.ownerType from tbl_EVT_Events e with (nolock) where e.ownerType = @ownertype and e.ownerId = @ownerId and #applyFilter( attributes.datastore.filter )# ), eventDays as ( select e.*, ed.apptDurationMinutes, c.calendarName boothName, c.calendarId as boothId, c.calendarId, ed.eventDate from getData e inner join tbl_EVT_Eventdates ed with (nolock) on e.eventId = ed.eventId inner join tbl_WRK_Calendars c with (nolock) on c.linkType = 'EVT' and c.linkid = ed.eventId ), appointments as ( select c.*, convert(varchar, a.startTime, 120) startTime, convert(varchar, dateadd(minute, duration, a.startTime), 120) endTime, a.contactId, a.partnerId, a.partnerType, a.appointmentId from eventDays c left outer join tbl_WRK_Appointments a with (nolock) on a.calendarId = c.boothId and a.ownerid = c.ownerid and a.ownerType = c.ownerType and cast(a.startTime as date) = c.eventDate ), distributor as ( select a.*, cdr.cdr_dstName, cdr_recordId, coalesce( img.ContentPath , imgP.ContentPath ) image from appointments a inner join tbl_CDR_Distributors cdr with (nolock) on cdr.cdr_recordId = a.partnerId and a.ownerid = cdr.ownerid and a.ownerType = cdr.fsl_tableCode left outer join tbl_DST_Distributors dst with (nolock)on cdr.fsl_dstId = dst.dstid left outer join tbl_DST_Distributors pdst with (nolock) on dst.dstparentco = pdst.dstid left outer join qryContentFullPathLookup img on dst.dstlogo = img.ContentID left outer join qryContentFullPathLookup imgP on pdst.dstlogo = imgP.ContentID ), contacts as ( select a.*, m.firstName, m.lastName, m.email from distributor a left outer join tbl_FSPro_members m with (nolock) on m.fspro_userid = a.contactId and m.orgId = a.cdr_recordId and m.orgType = 'CDRD' ), endDate as ( select max(eventDate) as endDate, ed.eventId from tbl_EVT_Eventdates ed inner join getData on ed.eventId = getData.eventID where 1 = 1 group by ed.eventId ), startDate as ( select min(eventDate) as startDate, ed.eventId from tbl_EVT_Eventdates ed inner join getData on ed.eventId = getData.eventID where 1 = 1 group by ed.eventId ), getEventDates as ( select c.*, startDate.startDate conferenceStartDate, endDate.endDate conferenceEndDate from contacts c inner join endDate on c.eventID = endDate.eventID inner join startDate on c.eventID = startDate.eventID where 1 = 1 ), allData as ( select distinct * from getEventDates ), data as ( select * from allData where 1 = 1 ) #forJSON( 'data', attributes.datastore, _defaultSortField )#