select category_name,parent_category_name from tbl_product p
left join
(
select cp.category_code,
case
when
cp.parent_code = 0 then ''
when
cp.parent_code != 0 then cp.category_name
end as category_name,
cp.parent_code, isnull(ch.category_name, cp.category_name) as parent_category_name from tbl_category cp
left join
(
select cl.category_name, cl.category_code, cl.parent_code from tbl_category cl
) ch on cp.parent_code = ch.category_code
) as cat
on cat.category_code = p.category_code
solved How to select data from the following table?