各レコードの GUID を含む複数の列を持つ 1 つの行に複数の子レコードを取得する方法を探していました...
テーブルは次のようになります:
StudentParentID StudentID ParentID
1
1
1
2 1 2
3 1 3 4
2
4
5 2 5
私が望むのは次のような結果セットです: )
SQL Server 2008 を使用しています。ご協力ありがとうございます。
各レコードの GUID を含む複数の列を持つ 1 つの行に複数の子レコードを取得する方法を探していました...
テーブルは次のようになります:
StudentParentID StudentID ParentID
1
1
1
2 1 2
3 1 3 4
2
4
5 2 5
私が望むのは次のような結果セットです: )
SQL Server 2008 を使用しています。ご協力ありがとうございます。
ピボットとランクを使用して実行できます。
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 を使用している場合は、もう少し注意が必要です。min() を使用するには、GUID を BINARY にキャストする必要があります。
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