Question

I have a query that returns only 1 row, as it should, I want to get the children related to this one parent ow but I want it flattened out. I want to add the children to the end of the query as fields.

So I have my results in a temp table now, and I can select this table and these are the results: select * from #Children

Row LastName    FirstName   MiddleName  A-Number    StatusID    DateOfBirth
1   Chu     Da Chi      NULL    NULL    26616   00:00.0
2   Chu     Herbert     NULL    NULL    26958   00:00.0
3   Chu     Herberta    NULL    NULL    26959   00:00.0
4   Chu     Mini        NULL    NULL    166325  59:30.0
5   Chu     Qwerty      NULL    NULL    212792  00:00.0
6   Chu     Xiao Chi    NULL    NULL    26615   00:00.0

I want these rows to appear at the end of the single row like this:

ParentID Child1FirstName Child2Firstname Child3Firstname, etc...

No correct solution

OTHER TIPS

Try this

SET NOCOUNT ON;

DECLARE @#TempTable TABLE (FirstName VARCHAR(50));

INSERT INTO @#TempTable
SELECT FirstName from #Children

DECLARE @result  varchar(8000) = 'ParentID',
        @FirstName  varchar(50);

WHILE EXISTS (SELECT * FROM  @#TempTable)
BEGIN
    SELECT TOP 1 @FirstName = FirstName FROM @#TempTable;

    SET @result += ' ' + @FirstName;

    DELETE  @#TempTable Where FirstName = @FirstName;
END

PRINT @result;
SELECT ParentID
      ,MAX(CASE WHEN Row = 1 THEN FirstName ELSE NULL END) AS Child1FirstName
      ,MAX(CASE WHEN Row = 2 THEN FirstName ELSE NULL END) AS Child2FirstName
      ,MAX(CASE WHEN Row = 3 THEN FirstName ELSE NULL END) AS Child3FirstName
      ...
FROM #Children
GROUP BY ParentID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top