select cdr.cdr_recordId, cdr.cdr_dstName, cdr.cdr_dstCode, pcdr.cdr_dstName parent_cdr_dstName, pcdr.cdr_recordId parent_cdr_recordId, cdr.cdr_territoryId, case when dst.dstCompanyType = 'B' and dst.dstParentCo > 0 then dst.dstParentCo else dst.dstId end as parentDstId from tbl_CDR_Distributors cdr with (nolock) left join tbl_DST_Distributors dst with (nolock) on dst.dstId = cdr.fsl_dstId and dst.dstParentCo > 0 left outer join tbl_CDR_Distributors pcdr with (nolock) on pcdr.fsl_dstId = dst.dstParentCo and pcdr.ownerId = cdr.ownerId and pcdr.fsl_tablecode = cdr.fsl_tablecode where cdr.ownerId = and cdr.fsl_tablecode = and cdr.cdr_recordId = select lastInvoiceDate from tbl_CRM_FiscalCalendar where ownerId = and ownerType = and fiscalYear =