将行值转换为SQL Server中的列(PIVOT)

时间:2013-06-04 11:19:15

标签: sql sql-server-2008 pivot

我在SQL Server中有一个名为 test 的表,有3列

|  ITEM | ATTRIBUTE | VALUE |
-----------------------------
| item1 |   Quality |     A |
| item1 |     color |   Red |
| item2 |   Quality |     B |
| item2 |     color | Black |

我想要这样的输出:

|  ITEM | QUALITY | COLOR |
---------------------------
| item1 |       A |   Red |
| item2 |       B | Black |

如何在SQL Server中获取此功能。

2 个答案:

答案 0 :(得分:4)

试试这个:

SELECT *
FROM (SELECT Item, attribute, value FROM MyTable) AS t
PIVOT
(
  MAX(value)
  FOR attribute IN([Quality], [Color])
) AS p;

输出:

╔═══════╦═════════╦═══════╗
║ ITEM  ║ QUALITY ║ COLOR ║
╠═══════╬═════════╬═══════╣
║ item1 ║ A       ║ Red   ║
║ item2 ║ B       ║ Black ║
╚═══════╩═════════╩═══════╝

请参阅this SQLFiddle

如果您不知道attribute的具体值:

,也可以使用此动态查询
DECLARE @cols AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(attribute) 
                    from MyTable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


set @query = 'SELECT Item,' + @cols + ' 
             from 
             (
                Select Item, attribute , value
                from MyTable
             ) dta
             pivot 
             (
                MAX(Value)
                for attribute in (' + @cols + ')
             ) pvt '

execute(@query);

请参阅this SQLFiddle

答案 1 :(得分:1)

对于mysql来说这是一个hacky解决方案,因为PIVOT不能在其中工作。

select item, GROUP_CONCAT('',q) as Quantity, GROUP_CONCAT('',c) as Color from 
(select item ,CASE WHEN attribute = 'Quality' THEN value ELSE NULL END as q, CASE WHEN attribute = 'Color' THEN value ELSE NULL END as c 
 from MyTable
) temp 
group by item

此解决方案的问题是您应该知道属性列的所有不同值。

您可以尝试here.