我有这样的数据我只想将行转换为列
以下数据
DECLARE @Table1 TABLE
( id int, name varchar(20), val varchar(20))
;
INSERT INTO @Table1
( id , name , val )
VALUES
(222, 'ram', 'match'),
(222, 'ra', 'nomatch'),
(222, 'man', 'nomatch'),
(222, 'kim', 'match')
;
我需要这样的输出
ID Match NoMatch
222 ram,kim ra,man
实际上我已经尝试过Pivot和Max Condition一些我错过了Point。
答案 0 :(得分:2)
试试这个:
SELECT id,
STUFF((SELECT ',' + name
FROM @Table1 t2
WHERE t2.id = t1.id AND val = 'match'
FOR XML PATH('')), 1, 1, '') AS Match,
STUFF((SELECT ',' + name
FROM @Table1 t2
WHERE t2.id = t1.id AND val = 'nomatch'
FOR XML PATH('')), 1, 1, '') AS Nomatch
FROM @Table1 t1
GROUP By id