将多个子记录ID输出到一行

时间:2013-06-14 01:18:27

标签: sql sql-server-2008

我一直在寻找一种方法来将多个子记录放到一行,其中多列包含每条记录的GUID ......

这是表格的样子:
StudentParentID StudentID ParentID
1 1 1
2 1 2
3 1 3
4 2 4
5 2 5
  
我想要的是一个结果集如下:
  
StudentID ParentID1 ParentID2 ParentID3
1 1 2 3
2 4 5(null)
  
我正在使用SQL Server 2008.感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

你可以使用pivot和rank来实现:

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