将行中的值转换为SQL Server(PIVOT)中的列 [英] Convert row value in to column in SQL server (PIVOT)

查看:51
本文介绍了将行中的值转换为SQL Server(PIVOT)中的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have table in SQL Server called test having 3 column

|  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中获得它.

How can I get this in SQL Server.

推荐答案

尝试以下方法:

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的具体值,也可以使用此动态查询:

See this SQLFiddle

You can also use this dynamic query if you don't know the specific value of 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);

这篇关于将行中的值转换为SQL Server(PIVOT)中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆