我会使用纯 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'
执行(@查询)
删除临时表
DROP TABLE #T