11

我在 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 中得到这个。

4

3 回答 3

15

试试这个:

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 ║
╚═══════╩═════════╩═══════╝

看到这个 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);

看到这个 SQLFiddle

于 2013-06-04T11:28:47.253 回答
4

这对于 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

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

你可以在这里试试

于 2018-02-28T04:50:57.327 回答
0

也可以使用字符串聚合,

SELECT item, STRING_AGG(CAST(q AS STRING)) AS Quantity, STRING_AGG(CAST(c AS STRING)) 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
于 2021-10-04T17:05:43.577 回答