I have 2 tables, where Customer table has customer data and relations table has relations of customer.
CREATE Table Customer
(
id int,
name nvarchar(10)
)
INSERT INTO Customer Values
(1, 'aaa'),
(2, 'bbb'),
(3, 'ccc'),
(4, 'ddd'),
(5, 'eee'),
(6, 'fff'),
(7, 'ggg'),
(8, 'hhh'),
(9, 'iii'),
(10, 'jjj'),
(11, 'kkk'),
(12, 'lll')
CREATE TABLE Relations
(
id int,
parentid int
)
INSERT INTO Relations VALUES
(2, 1),
(3, 1),
(4, 2),
(5, 2),
(6, 1),
(7, 4),
(8, 5),
(9, 8),
(10, 8),
(12, 7)
I want to find GrandParent, Parent and child by ID. For Ex: If I want to find all relations of ID=4, I should get the result in the below format. Ordered by Grand Parent at the top if the ID has a parent or Grand parent. If not, then it has to show the child of that ID.
Grand Parent | aaa
Parent | bbb
Child | ggg
Child | lll
Could you please help me with the above query in "SQL Server".