0

我有一个表和一个返回这些结果的选择查询:

[Individual]    [team]       [Score]   
----------------------------------------
 x              Man U        Conversion
 x              Man U        Penalty
 x              Man U        Drop Goal
 y              Arsenal      goal   

在我的存储过程中,我想将结果返回为:

[individual]     [team]     [1]            [2]          [3]         [4]        
x                Man U      Conversion     penalty      Drop Goal   Goal 
y                Arsenal    goal

由于数据库兼容性,我不能使用数据透视表。

请使用代码示例建议替代方案

4

1 回答 1

0

这是使用游标、一些动态 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
于 2013-04-16T16:04:11.090 回答