Это моё решение вашей проблемы, которую я только что взломал. Без комментариев или чего-либо еще, я боюсь, но, надеюсь, это даст вам отправную точку.
со стартовым столом #Jobs
вот так:
JobNumber SplitValue
--------- ----------
J1 X1
J1 X2
J1 X3
J2 X1
J2 X2
J2 X3
Вы получите вывод этого:
JobNumber col_0 col_1 col_2
--------- ----- ----- -----
J1 X1 X2 X3
J2 X1 X2 X3
Код:
CREATE TABLE #Jobs
(
JobNumber varchar(2),
SplitValue varchar(2)
)
INSERT INTO #Jobs (JobNumber, SplitValue) VALUES ('J1','X1')
INSERT INTO #Jobs (JobNumber, SplitValue) VALUES ('J1','X2')
INSERT INTO #Jobs (JobNumber, SplitValue) VALUES ('J1','X3')
INSERT INTO #Jobs (JobNumber, SplitValue) VALUES ('J2','X1')
INSERT INTO #Jobs (JobNumber, SplitValue) VALUES ('J2','X2')
INSERT INTO #Jobs (JobNumber, SplitValue) VALUES ('J2','X3')
SELECT * FROM #Jobs
DECLARE @ColumnsNeeded int
;WITH CountsTable AS
(
SELECT COUNT(*) AS ColumnCount FROM #Jobs GROUP BY JobNumber
)
SELECT @ColumnsNeeded = MAX(ColumnCount) FROM CountsTable
DECLARE @Counter int
SET @Counter = 0
CREATE TABLE #Pivoted
(
JobNumber varchar(2)
)
DECLARE @AddColumnCommandPre varchar(255)
DECLARE @AddColumnCommandPost varchar(255)
DECLARE @AddColumnCommand varchar(255)
SET @AddColumnCommandPre = 'ALTER TABLE #Pivoted ADD col_'
SET @AddColumnCommandPost = ' varchar(2)'
WHILE (@Counter < @ColumnsNeeded)
BEGIN
SET @AddColumnCommand = @AddColumnCommandPre + CAST(@Counter as varchar(3)) + @AddColumnCommandPost
EXECUTE (@AddColumnCommand)
SELECT @Counter = @Counter + 1
END
SELECT * INTO #JobsWithRowNum FROM #Jobs
ALTER TABLE #JobsWithRowNum ADD RowNum int IDENTITY(1,1)
CREATE CLUSTERED INDEX JobsWithRowNum_RowNum ON #JobsWithRowNum(RowNum)
DECLARE @RowCount int
SELECT @RowCount = COUNT(*) FROM #JobsWithRowNum
DECLARE @RowInsert varchar(255), @Columns varchar(255), @Data varchar(255)
DECLARE @LastJobNumber varchar(3), @CurrentJobNumber varchar(3)
DECLARE @ColumnCounter int
SET @RowInsert = 'INSERT INTO #Pivoted (JobNumber'
SET @Columns = ''
SELECT @LastJobNumber = JobNumber FROM #JobsWithRowNum WHERE RowNum = 1
SET @Data = ') VALUES (''' + @LastJobNumber
SET @Counter = 1
SET @ColumnCounter = 0
WHILE (@Counter <= @RowCount)
BEGIN
SELECT @CurrentJobNumber = JobNumber FROM #JobsWithRowNum WHERE RowNum = @Counter
IF @CurrentJobNumber <> @LastJobNumber
BEGIN
EXEC (@RowInsert + @Columns + @Data + ''')')
SET @Data = ') VALUES (''' + @CurrentJobNumber
SET @LastJobNumber = @CurrentJobNumber
SET @ColumnCounter = 0
SET @Columns = ''
END
SET @Columns = @Columns + ', col_' + CAST(@ColumnCounter AS varchar(3))
SELECT @Data = @Data + ''', ''' + SplitValue FROM #JobsWithRowNum WHERE RowNum = @Counter
SET @Counter = @Counter + 1
SET @ColumnCounter = @ColumnCounter + 1
END
EXEC (@RowInsert + @Columns + @Data + ''')')
SELECT * FROM #Pivoted
DROP TABLE #JobsWithRowNum
DROP TABLE #Pivoted
DROP TABLE #Jobs