この問題を解決するには、純粋なSQLの方法を使用します。だからここにあなたのための提案があります:
テストデータ
CREATE TABLE #T
(
ItemID VARCHAR(100),
ProcessID VARCHAR(100),
Sequence INT
)
INSERT INTO #T
VALUES
('Item 1','ProcessA',1),
('Item 1','ProcessB',2),
('Item 3','ProcessA',1),
('Item 2','ProcessA',1),
('Item 1','ProcessC',3),
('Item 3','ProcessB',2)
ピボットの列
DECLARE @cols VARCHAR(MAX)
;WITH CTE
AS
(
SELECT
ROW_NUMBER() OVER(PARTITION BY Sequence ORDER BY Sequence) AS RowNbr,
'Sequence '+CAST(t.Sequence AS VARCHAR(10)) AS Sequence
FROM
#T AS t
)
SELECT @cols=STUFF
(
(
SELECT
',' +QUOTENAME([Sequence])
FROM
CTE
WHERE CTE.RowNbr=1
FOR XML PATH('')
)
,1,1,'')
動的ピボットを実行する
DECLARE @query NVARCHAR(4000)=
N'SELECT
*
FROM
(
SELECT
t.ItemID,
t.ProcessID,
''Sequence ''+CAST(t.Sequence AS VARCHAR(10)) AS Sequence
FROM
#T AS t
) AS SourceTable
PIVOT
(
MAX(ProcessID)
FOR Sequence IN ('+@cols+')
) AS p'
EXECUTE(@クエリ)
一時テーブルを削除する
DROP TABLE #T