1

I have been searching for a way to get multiple child records to one row with multiple columns containing the GUID of each record...

Here is what the table looks like:
StudentParentID StudentID ParentID
1 1 1
2 1 2
3 1 3
4 2 4
5 2 5

What I'd like is a result set like:

StudentID ParentID1 ParentID2 ParentID3
1 1 2 3
2 4 5 (null)

I am using SQL Server 2008. Thank you for your help!

4

1 回答 1

1

您可以使用枢轴和排名来做到这一点:

select StudentID, [1] as P1, [2] as P2, [3] as P3 from (
  select StudentID, ParentID, RANK() over (PARTITION BY StudentID ORDER BY ParentID) as rnk
  from STUDENT_PARENTS
) ranked PIVOT (min(ParentID) for rnk in ([1], [2], [3])) as p

在 SqlFiddle 上查看:

http://sqlfiddle.com/#!3/e3254/9

如果您使用的是 GUID,那就有点棘手了,您需要将它们转换为 BINARY 才能使用 min():

select StudentID, 
    cast([1] as uniqueidentifier) as P1, 
    cast([2] as uniqueidentifier) as P2, 
    cast([3] as uniqueidentifier) as P3 
from (
  select StudentID, cast(ParentID as binary(16)) as ParentID, RANK() over (PARTITION BY StudentID ORDER BY StudentParentID) as rnk
  from STUDENT_PARENTS
) ranked PIVOT (min(ParentID) for rnk in ([1], [2], [3])) as p

SqlFiddle 这里:http ://sqlfiddle.com/#!3/8d0d7/14

于 2013-06-14T01:40:29.447 回答