I've been struggling trying to write the logic to show a relationship between interrelated records.
Here is some sample data to show what I'm trying to accomplish:
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
Expected Results:
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
I tried to accomplish this through a recursive CTE, but I had not luck.
Here is one solution
;WITH T AS (
SELECT
ROW_NUMBER() OVER (ORDER BY item_id) AS group_id,
*
FROM #temp_data T
WHERE related_item_Id IS NULL
UNION ALL
SELECT T.group_id, T1.*
FROM T
INNER JOIN #temp_data T1
ON T.item_id = T1.related_item_id
)
SELECT * FROM T ORDER BY group_id, item_id
The output is
group_id item_id item_name related_item_id related_item_name
-------------------- ----------- --------------- --------------- -----------------
1 10 apple 20 orange
1 20 orange 30 grape
1 30 grape 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.