你可以检查这个小提琴
它由一个 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)