3

Given a typical closure table, how would I write a query to get a list of ids back to the root? Is there a way to do that for all the [unique] ids? I'm using Microsoft SQL Server.

Given:

parent child depth
1 1 0
2 2 0
3 3 0
1 2 1
2 3 1
1 3 2

I'd like:

id path
1 1
2 1,2
3 1,2,3

Does that make sense?

Paul White
95.3k30 gold badges439 silver badges689 bronze badges
asked May 25, 2016 at 15:35

1 Answer 1

4

Looks like a GROUP_CONCAT to me, unless I'm missing something, eg

CREATE TABLE #heredity
(
 parent INT NOT NULL,
 child INT NOT NULL,
 depth INT NOT NULL,
CONSTRAINT _pk_heredity PRIMARY KEY ( parent, child )
);
GO
INSERT INTO #heredity ( parent, child, depth )
VALUES
 ( 1, 1, 0 ),
 ( 2, 2, 0 ),
 ( 3, 3, 0 ),
 ( 1, 2, 1 ),
 ( 2, 3, 1 ),
 ( 1, 3, 2 );
GO
SELECT 
 child,
 STUFF(
 (
 SELECT ',' + CAST( parent AS VARCHAR(20) )
 FROM #heredity p
 WHERE c.parent = p.child
 ORDER BY parent DESC
 FOR XML PATH(''), TYPE
 ).value('.', 'VARCHAR(100)'),
 1, 1,'') AS [path]
FROM #heredity c
WHERE depth = 0;

My results:

Test Results

answered May 25, 2016 at 16:12
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.