使用列的值到另一个列名称

时间:2013-08-27 11:43:22

标签: sql sql-server

以下是值:

id      |   cat    |    AttribGroup  |  AttribID   |   Value
1            1           test             001          beautiful
1            1           test             002          handsome

现在我想要发生的事情是:

id      |   cat    |    test_001     |  test_002  
1            1         beautiful        handsome

1 个答案:

答案 0 :(得分:2)

您可以查看this fiddle

它由一个PIVOT组成,然后将结果连接到初始表。

因为我猜你的值不仅仅是test_001和test_002,所以你需要一些动态SQL才能定义列。

代码:

DECLARE @cols AS VARCHAR(MAX),
        @query AS VARCHAR(MAX)

SET @cols = STUFF((SELECT distinct ',[' + AttribGroup + '_' + AttribID +']'
            FROM Table1 c
            FOR XML PATH(''), TYPE
            ).value('.', 'VARCHAR(MAX)') 
        ,1,1,'')


SET @query = 
';WITH MyCTE AS
(
    SELECT    * 
    FROM 
    (
        SELECT    AttribGroup + ''_'' + AttribID  AS ColName, 
                  CONVERT(VARCHAR,id)+''_''+CONVERT(VARCHAR,cat) AS idcat, 
                  Value
        FROM      Table1
    ) p
    PIVOT 
    (
        MAX    (Value)
        FOR    ColName IN (' + @cols + ')
    )   AS pvt
)

SELECT    t.id,
          t.cat,
          m.* 
FROM      MyCTE m
          JOIN 
          (
              SELECT    id,
                        cat,
                        CONVERT(VARCHAR,id)+''_''+CONVERT(VARCHAR,cat) as idcat
              FROM      Table1
              GROUP BY  id,
                        cat
          ) t
              ON m.idcat = t.idcat'


EXEC(@query)