declare @ownerId int = ; declare @ownerType varchar(3) = ; with memberGroupsRaw as ( select cho.cho_type as oprCompanyType, opr.companyName, cho.cho_id, opr.operatorId, cho.cho_name, row_number() over ( partition by opr.fsl_choId order by operatorId ) as mappingPriority from tbl_OPR_ClientOperators opr with (nolock) inner join tbl_CHO_Operators cho with (nolock) on cho.cho_id = opr.fsl_choId where opr.ownerId = @ownerId and opr.fsltablecode = @ownerType and opr.oprCompanyType in ( 'C', 'G' ) and cho.cho_type = ), memberGroups as ( select oprCompanyType, companyName, cho_id, operatorId, cho_name from memberGroupsRaw with (nolock) where mappingPriority = 1 ) #forJSON( 'memberGroups', attributes.dataStore, 'companyName' )#