答案 0 :(得分: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
答案 1 :(得分:0)
您需要LEFT JOIN
自己,如下所示。
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