【发布时间】:2014-12-19 11:19:41
【问题描述】:
我一直在努力编写逻辑来显示相关记录之间的关系。
这里有一些示例数据来展示我想要完成的工作:
CREATE TABLE #temp_data
(
item_id int,
item_name varchar(100),
related_item_id int,
related_item_name varchar(100)
)
INSERT INTO #temp_data
select 10, 'apple', 20 , 'orange' UNION ALL
select 20, 'orange', 30 , 'grape' UNION ALL
select 30, 'orange', NULL , NULL UNION ALL
select 100, 'tomato', 200 , 'onion' UNION ALL
select 200, 'onion', 300 , 'tomato' UNION ALL
select 400, 'cucumber',100 , 'tomato' UNION ALL
select 300, 'pepper', NULL , NULL UNION ALL
select 500, 'lettuce', 400 , 'cucumber' UNION ALL
select 1000, 'beef' , NULL, NULL UNION ALL
select 10000, 'cheese, NULL, NULL
预期结果:
group_id item_id item_name related_item_id related_item_name
1 10 apple 20 orange
1 20 orange 30 grape
1 30 orange NULL NULL
2 100 tomato 200 onion
2 200 onion 300 tomato
2 300 pepper NULL NULL
2 400 cucumber 100 tomato
2 500 lettuce 400 cucumber
3 1000 beef NULL NULL
4 10000 cheese NULL NULL
我试图通过递归 CTE 来实现这一点,但我没有运气。
【问题讨论】:
-
请编辑您的帖子以显示您尝试的 CTE,以及结果有什么问题。
-
上面发布的数据只是一些示例数据,用于说明示例。我试图弄清楚如何编写逻辑来显示具有匹配 item_id/related_item_ids 的记录之间的关系。例如,A = B 和 B = C,我在编写显示 A = C 的逻辑时遇到了麻烦。
-
会不会有一组项目其中一个没有
related_item_id = NULL?关系总是一棵简单的树,还是项目之间的关系存在循环?如果其中任何一个是正确的,那么答案将是不同的。示例数据的一个关键部分是确保它完全捕捉到与您的实际数据集相关的细微差别和复杂性。 -
Mellamokb,这很好。是的,你给出的例子可能会发生。我已经更新了我的示例数据以反映这一点。
标签: sql sql-server tsql recursion hierarchy