2016-08-11 9 views

答えて

0
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 
0

結果を得るための方法

enter image description here

として。

SELECT 
    T.categroy_name, 
    COALESCE(Parent.category_name, '') AS 'parent category' 
FROM 
    Tbl T LEFT JOIN 
    Tbl Parent ON T.parent_code = Parent.categrory_code 
1

予想される出力が混乱の原因です。私はあなたが出力として以下のフォーマットを期待していると思った。

DECLARE @CategoriesDetails TABLE (category_code INT, parent_code INT, category_name VARCHAR(100)); 

INSERT INTO @CategoriesDetails (category_code, parent_code, category_name) VALUES 
(1, 0, 'Food'), 
(2, 1, 'Bakery'), 
(3, 2, 'Snaks'); 

SELECT C1.category_name AS [Sub category], 
     ISNULL(C2.category_name, '') AS [Parent category] 
FROM @CategoriesDetails C1 
LEFT JOIN @CategoriesDetails C2 ON C2.category_code = C1.parent_code 

出力:

Sub category Parent category 
-------------------------------- 
Food    
Bakery   Food 
Snaks   Bakery 
関連する問題