将行转换为列SQL 2008

时间:2011-06-06 05:58:19

标签: sql sql-server-2008

我只想转换下表

RegionID Region RedionCode RegionSupervisor

1     Eastern    E01         Mark
2     Western    W01         Jim
3     Northern    N01        Paul
4     Southern    S01        David

南部东部西部

1          2         3            4
E01        W01       N01          S01
Mark       Jim       Paul         David

我使用的是SQL 2008.任何帮助都会非常感激

喝彩!

3 个答案:

答案 0 :(得分:4)

您可以使用PIVOT and UNPIVOT tsql命令执行此操作。

答案 1 :(得分:1)

您可以使用PIVOT,但您还需要合并动态SQL,因为PIVOT本身只支持您事先知道结果表中的完整列集的情况。 Pivots with Dynamic Columns in SQL Server 2005

答案 2 :(得分:0)

好的,最后我找到了一种方法,但可能不是更有效的方法。我找不到PIVOT的解决方案

BEGIN
    DECLARE @ColumnList varchar(200)
    DECLARE @ColumnInList varchar(200)
    DECLARE @TableName varchar(20)
    DECLARE @TableScript varchar(2000)                         

    SET @ColumnList = ''
    SET @ColumnInList = ''
    SELECT @ColumnInList += RTRIM(RegionDescription) + ',', @ColumnList += '[' + RTRIM(RegionDescription) + '] varchar(50) , '
    FROM RegionSup 

    SET @ColumnList = LEFT(@ColumnList, LEN(@ColumnList) - 1)
    SET @ColumnInList = LEFT(@ColumnInList, LEN(@ColumnInList) - 1)

    SELECT @TableName = 'TEMP' + CONVERT(char(12),GETDATE(),14);
    SELECT @TableName = REPLACE(@TableName,':','')
    SET @TableScript = 'CREATE TABLE ' + @TableName + ' (' +
                    @ColumnList + ')'

    EXECUTE (@TableScript)


    --Column Values
    DECLARE @RegionID varchar(30)
    DECLARE @RegionSupervisor varchar(50)
    DECLARE @RegionCode varchar(50)
    --End Column Values

    SET @RegionID = ''
    SET @RegionSupervisor = ''
    SET @RegionCode = ''

    SELECT @RegionID += '''' + CONVERT(varchar(10),RegionID) + ''',',
           @RegionSupervisor += '''' + RegionSupervisor + ''',',
           @RegionCode +=  '''' + RegionCode + ''','
    FROM RegionSup

    SET @RegionID = LEFT(@RegionID,LEN(@RegionID) - 1)
    SET @RegionSupervisor = LEFT(@RegionSupervisor,LEN(@RegionSupervisor) - 1)
    SET @RegionCode = LEFT(@RegionCode,LEN(@RegionCode) - 1)

    DECLARE @InsertStatement nvarchar(max)
    SET @InsertStatement = ''

    SET @InsertStatement = 'INSERT INTO ' + @TableName + '(' +  @ColumnInList + ') VALUES ' +
                            '(' + @RegionID + '),' +
                            '(' + @RegionSupervisor + '),' +
                            '(' + @RegionCode + ')' 

    EXECUTE(@InsertStatement)                       

    EXECUTE('SELECT * FROM ' + @TableName)
    EXECUTE('DROP TABLE ' + @TableName)
END