0

我有一个只返回 1 行的查询,正如它应该的那样,我想获取与这个父母相关的孩子,但我希望它变平。我想将孩子作为字段添加到查询的末尾。

所以我现在在一个临时表中有我的结果,我可以选择这个表,这些是结果: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

我希望这些行出现在单行的末尾,如下所示:

ParentID Child1FirstName Child2Firstname Child3Firstname, etc...
4

2 回答 2

0

尝试这个

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;
于 2013-11-15T04:04:53.520 回答
-1
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
于 2013-11-15T07:53:35.687 回答