Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Parent - Child data in one table

$
0
0

Hi All,

I have table which has columns Id, Name, ParentId. I need data from this table, first one parent followed by its children and then next parent followed by its children.

CREATE TABLE #t1
(id INT,brand VARCHAR(10),parent_id INT)

INSERT INTO #t1
        ( id, brand, parent_id )
VALUES  ( 1, -- id - int
          'a', -- brand - varchar(10)
          null  -- parent_id - int
          )
          
INSERT INTO #t1
        ( id, brand, parent_id )
VALUES  ( 2, -- id - int
          'b', -- brand - varchar(10)
          null  -- parent_id - int
          )
          
INSERT INTO #t1
        ( id, brand, parent_id )
VALUES  ( 3, -- id - int
          'c', -- brand - varchar(10)
          1  -- parent_id - int
          )

INSERT INTO #t1
        ( id, brand, parent_id )
VALUES  ( 4, -- id - int
          'd', -- brand - varchar(10)
          2  -- parent_id - int
          )

INSERT INTO #t1
        ( id, brand, parent_id )
VALUES  ( 5, -- id - int
          'e', -- brand - varchar(10)
          1  -- parent_id - int
          )

need output as

Id,Brand,ParentId,ParentBrand 

1,a,null,null

3,c,1,a

5,e,1,a

2,b,null,null

4,d,2,b

Thanks in advance


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>