with distribution as (
select distinct cs.customersku,
case when cs.customertype = 'byg'
then bg.name
else cdr.cdr_dstname
end as dstname
from tbl_PRD_CustomerSkus cs with (nolock)
inner join tbl_PRD_Skus s with (nolock)
on s.ownerid = cs.ownerid
and s.fsl_tableCode = cs.fsl_tableCode
and s.skuid = cs.skuid
left outer join tbl_CDR_Distributors cdr with (nolock)
on cdr.cdr_recordid = cs.customerid
and cdr.ownerid =
and cdr.fsl_tablecode =
and (
cs.customertype = 'pdst' or
( cs.customertype = 'dst' and cdr.cdr_territoryid in ( ) )
)
left outer join tbl_byg_buyinggroups bg with (nolock)
on bg.uniqueid = cs.customerid
and cs.customertype = 'byg'
where cs.OwnerID =
and cs.FSL_TableCode =
and cs.skuid =
and rtrim(coalesce(s.sku,'')) <> rtrim(coalesce(cs.CustomerSku,''))
)
select *
from distribution
where nullif(dstname,'') is not null
order by dstname