Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 515855
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T07:40:16+00:00 2026-05-13T07:40:16+00:00

Let’s asume I have a parent-child structure setup in SQL (server 2005): CREATE TABLE

  • 0

Let’s asume I have a parent-child structure setup in SQL (server 2005):

CREATE TABLE parent (Id INT IDENTITY PRIMARY KEY, Name VARCHAR(255))
CREATE TABLE child (Id INT IDENTITY PRIMARY KEY, parentId INT, Name VARCHAR(255))

insert into parent select 'parent with 1 child'
insert into parent select 'parent with 2 children'

insert into child(name, parentid) select 'single child of parent 1', 1
insert into child(name, parentid) select 'child 1 of 2 of parent 2', 2
insert into child(name, parentid) select 'child 2 of 2 of parent 2', 2

Is there a way to return one row per parent with it’s children as columns? Like:

parent.Id, parent.Name, child(1).Id, child(1).Name, child(2).Id, child(2).Name

Started out with:

select * from parent p
    left outer join child c1 on c1.parentid = p.id
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T07:40:17+00:00Added an answer on May 13, 2026 at 7:40 am

    Your example is close to pivoting, but I do not think that pivot functionality is usable on this one.

    I have renamed your example to use “department-person”, instead of “child-parent”, just to keep my sanity.

    So, first tables and some data

    DECLARE @Department TABLE
      ( 
       DepartmentID int
      ,DepartmentName varchar(50)
      )
    DECLARE @Person TABLE
      ( 
       PersonID int
      ,PersonName varchar(50)
      ,DepartmentID int
      )
    
    INSERT  INTO @Department
      ( DepartmentID, DepartmentName )
     SELECT 1, 'Accounting' UNION
     SELECT 2, 'Engineering' UNION
     SELECT 3, 'Sales' UNION
     SELECT 4, 'Marketing' ;
    
    INSERT  INTO @Person
      ( PersonID, PersonName, DepartmentID )
     SELECT 1, 'Lyne', 1 UNION
     SELECT 2, 'Damir', 2 UNION
     SELECT 3, 'Sandy', 2 UNION
     SELECT 4, 'Steve', 3 UNION
     SELECT 5, 'Brian', 3 UNION
     SELECT 6, 'Susan', 3 UNION
     SELECT 7, 'Joe', 4 ;
    

    Now I want to flatten the model, I’ll use temporary table because I have table variables — but a view on “real tables” would be good too.

    /*  Create a table with:
        DepartmentID, DepartmentName, PersonID, PersonName, PersonListIndex
    
     This could be a view instead of temp table. 
    */
    IF object_id('tempdb.dbo.#tmpTbl','U') IS NOT NULL
     DROP TABLE #tmpTbl
    
    ;
    WITH  prs
            AS ( SELECT PersonID
                       ,PersonName
                       ,DepartmentID
                       ,row_number() OVER ( PARTITION BY DepartmentID ORDER BY PersonID ) AS [PersonListIndex]
                 FROM   @Person
               ),
          dptprs
            AS ( SELECT d.DepartmentID
                       ,d.DepartmentName
                       ,p.PersonID 
                       ,p.PersonName
                       ,p.PersonListIndex
                 FROM   @Department AS d
                        JOIN prs AS p ON p.DepartmentID = d.DepartmentID
               )
    SELECT * INTO #tmpTbl FROM dptprs
    
    -- SELECT * FROM #tmpTbl
    

    Dynamic columns means dynamic query, I will compose it row-by-row into a table

    /* Table to compose dynamic query */
    DECLARE @qw TABLE
      ( 
       id int IDENTITY(1, 1)
      ,txt nvarchar(500)
      )
    
    /* Start composing dynamic query */
    INSERT  INTO @qw ( txt ) VALUES  ( 'SELECT' ) 
    INSERT  INTO @qw ( txt ) VALUES  ( '[DepartmentID]' )
    INSERT  INTO @qw ( txt ) VALUES  ( ',[DepartmentName]' ) ;
    
    
    /* fetch max number of employees in a department */
    DECLARE @i int ,@m int
    SET @m = (SELECT max(PersonListIndex) FROM #tmpTbl)
    
    /* Compose dynamic query */
    SET @i = 1
    WHILE @i <= @m 
      BEGIN  
          INSERT  INTO @qw ( txt )
                SELECT  ',MAX(CASE [PersonListIndex] WHEN '
                        + cast(@i AS varchar(10)) + ' THEN [PersonID] ELSE NULL END) AS [Person_'
                        + cast(@i AS varchar(10)) + '_ID]'
    
          INSERT  INTO @qw ( txt )
                SELECT  ',MAX(CASE [PersonListIndex] WHEN '
                        + cast(@i AS varchar(10)) + ' THEN [PersonName] ELSE NULL END) AS [Person_'
                        + cast(@i AS varchar(10)) + '_Name]'  
    
        SET @i = @i + 1
      END
    
    /* Finish the dynamic query */
    INSERT  INTO @qw (txt) VALUES ( 'FROM #tmpTbl' )
    INSERT  INTO @qw (txt) VALUES ( 'GROUP BY [DepartmentID], [DepartmentName]' )
    INSERT  INTO @qw (txt) VALUES ( 'ORDER BY [DepartmentID]' )
    
    -- SELECT * FROM @qw
    

    And now, concatenate all query rows into a variable and execute

    /* Create a variable with dynamic sql*/
    DECLARE @exe nvarchar(4000)
    SET @exe=''
    SELECT  @exe = @exe + txt + ' ' FROM @qw ORDER BY id
    
    /* execute dynamic sql */
    EXEC master..sp_executesql @exe
    

    And here is the result:

    alt text

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 368k
  • Answers 368k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The Entity Framework designer is terrible - I've had the… May 14, 2026 at 5:11 pm
  • Editorial Team
    Editorial Team added an answer If by "hijack" you meant sniff the packets then what… May 14, 2026 at 5:11 pm
  • Editorial Team
    Editorial Team added an answer If you want two actions to be atomic, embed them… May 14, 2026 at 5:11 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.