将结果表从列更改为行

时间:2016-06-30 14:22:11

标签: sql-server tsql pivot

我有一张表格,结果如下:

Variablename|value|Stringvalue
---------------------------------   
Red            1        'Red'      
Green          8        null     
Purple         8        null     
Violet         3        'Violet'
Blue           2        'Blue'          

现在我希望将其转换为:

Red | Green | Purple | Violet | Blue
--------------------------------------
1       8       8        3        2
'Red'  null    null   'Violet'  'Blue'

我对Pivot和Unpivot很反感,但我似乎无法绕过那个

1 个答案:

答案 0 :(得分:3)

如果你真的想要那种格式的输出,你可以做两个支点并将它们结合在一起。必须将整数值转换为字符数据类型。此外,您需要确保使用正确的聚合。我根据这个例子选择了SUM和MAX,但这可能不是你真正想要的。

CREATE TABLE #MyTest (
    VariableName VARCHAR(25)
    ,Value INT
    ,StringValue VARCHAR(25)
    )

INSERT INTO #MyTest
VALUES (
    'Red',1 ,'Red')
    ,('Green',8,NULL)
    ,('Purple',8,NULL)
    ,('Violet',3,'Violet')
    ,('Blue',2,'Blue')

    SELECT CAST([Red] AS VARCHAR(25)) AS Red
    ,CAST([Green] AS VARCHAR(25)) AS Green
    ,CAST([Purple] AS VARCHAR(25)) AS Purple
    ,CAST([Violet] AS VARCHAR(25)) AS Violet
    ,CAST([Blue] AS VARCHAR(25)) AS Blue
FROM (
    SELECT VariableName
        ,Value
    FROM #MyTest
    ) AS a
PIVOT(SUM(Value) FOR VariableName IN (
            [Red]
            ,[Green]
            ,[Purple]
            ,[Violet]
            ,[Blue]
            )) AS pvt

UNION ALL

SELECT [Red]
    ,[Green]
    ,[Purple]
    ,[Violet]
    ,[Blue]
FROM (
    SELECT VariableName
        ,StringValue
    FROM #MyTest
    ) AS a
PIVOT(MAX(StringValue) FOR VariableName IN (
            [Red]
            ,[Green]
            ,[Purple]
            ,[Violet]
            ,[Blue]
            )) AS pvt