-1

以下是值:

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
4

1 回答 1

2

你可以检查这个小提琴

它由一个 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)
于 2013-08-27T11:53:29.340 回答