这是使用游标、一些动态 SQL 和 ROW_NUMBER() 的一种方法:
--declare input
DECLARE @input_table TABLE
(
[individual] CHAR(1),
[team] VARCHAR(10),
[score] VARCHAR(10)
)
INSERT INTO @input_table ([individual], [team], [score]) VALUES ('x', 'Man U', 'Conversion')
INSERT INTO @input_table ([individual], [team], [score]) VALUES ('x', 'Man U', 'Penalty')
INSERT INTO @input_table ([individual], [team], [score]) VALUES ('x', 'Man U', 'Drop Goal')
INSERT INTO @input_table ([individual], [team], [score]) VALUES ('y', 'Arsenal', 'Goal')
SELECT * FROM @input_table
--declare output
CREATE TABLE #output_table
(
[individual] CHAR(1),
[team] VARCHAR(10)
)
DECLARE @max_count INT
SET @max_count = (
SELECT
MAX([COUNT])
FROM
(
SELECT
[individual],
[team],
COUNT(*) AS [COUNT]
FROM @input_table
GROUP BY [individual], [team]
)result_set
)
--add columns
DECLARE @tmp_max_count INT
SET @tmp_max_count = 1
WHILE(@max_count >= @tmp_max_count)
BEGIN
DECLARE @dynamic_column_add VARCHAR(MAX)
SET @dynamic_column_add = 'ALTER TABLE #output_table ADD [' + CAST(@tmp_max_count AS VARCHAR(10)) + '] VARCHAR(10)'
EXEC (@dynamic_column_add)
SET @tmp_max_count = @tmp_max_count + 1
END
--populate non-dynamic columns
INSERT INTO #output_table ([individual], [team])
SELECT DISTINCT
[individual],
[team]
FROM
@input_table
--populate dynamic columns
DECLARE my_cursor CURSOR FOR
SELECT
'UPDATE #output_table SET [' + CAST([new_column] AS VARCHAR(10)) + '] = ''' + [score] + ''' WHERE [individual] = ''' + [individual] + ''' AND [team] = ''' + [team] + ''''
FROM
(
SELECT
[individual],
[team],
[score],
ROW_NUMBER() OVER (PARTITION BY [individual], [team] ORDER BY [individual], [team]) AS [new_column]
FROM
@input_table
)result_set
DECLARE @dynamic_statement VARCHAR(MAX)
OPEN my_cursor
FETCH NEXT FROM my_cursor INTO @dynamic_statement
WHILE (@@FETCH_STATUS = 0)
BEGIN
EXEC (@dynamic_statement)
FETCH NEXT FROM my_cursor INTO @dynamic_statement
END
CLOSE my_cursor
DEALLOCATE my_cursor;
SELECT * FROM #output_table
DROP TABLE #output_table