我有一个只返回1行的查询,因为它应该,我希望得到与这一个父级相关的子项,但我希望它变平。我想将子项添加到查询的末尾作为字段。
所以我现在将结果放在临时表中,我可以选择这个表,结果如下: 从#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...
答案 0 :(得分: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;
答案 1 :(得分:-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