---> declare @ownerId int = ; declare @ownerType varchar(3) = ; declare @timeframeDays int = ; with topOpps as ( select top #_topCount# partnerId, partnerType, partnerIdTk, partnerName, sum( cases ) cases, sum( lbs ) lbs, sum( dollars ) dollars , sum( equivUnits) equivUnits,sum( impactEquivUnits ) impactEquivUnits , sum( impactCases ) impactCases, sum( impactLbs ) impactLbs, sum( impactDollars ) impactDollars from tbl_DW_Opportunities#_tableSuffix# o with (nolock) where statusCode= 'C' and partnerType = 'OPR' and ownerId = @ownerId and ownerType = @ownerType and partnerTerritoryId in ( ) and effectiveRepId in ( ) and ( 1 = 2 or territoryPath like ) and budgetCategoryId in () and effectiveRepId in () and mfr_id in () and (1=2 or o.clientSegPath like ) o.clientSegPath like and effectiveRepOwnerType = and ( 1 = 2 or productSetTags like ) and estOrderDate >= dateAdd( day, @timeframeDays, getDate() ) and estOrderDate <= cast( getDate() as date ) -- this constraint observes both ends of the window, not just the start (above) group by partnerId, partnerIdTk, partnerType, partnerName order by #_measurementOption# desc ) #forJSON( 'topOpps', attributes.dataStore, '#_measurementOption#' )# attributes.dataStore.writeToLog( _r );