我有一张桌子
Title Name Type
------------------------------------------------
T1 A Primary
T1 B Primary
T2 B Primary
T2 C Secondary
T2 D Secondary
我需要输出
Title Primary Secondary
------------------------------------------------
T1 A, B NULL/Blank
T2 B C, D
原始表中的[Name]列可以有任何值。即后来可能有E,F,G等。
如何做到这一点?
答案 0 :(得分:8)
然后你需要动态SQL。考虑这样的事情来生成列列表:
DECLARE @collist nvarchar(max);
SELECT @collist = STUFF((SELECT ', ' + quotename(Type) FROM YourTable GROUP BY Type FOR XML PATH('')), 1, 2, '');
现在您可以使用@collist帮助构建所需的查询,然后使用sp_executesql
像这样:
DECLARE @collist nvarchar(max);
SELECT @collist = STUFF((SELECT ', ' + quotename(Type) FROM YourTable GROUP BY Type FOR XML PATH('')), 1, 2, '');
DECLARE @qry nvarchar(max);
SET @qry = N'
SELECT Title, ' + @collist + '
FROM
(
SELECT t.Title, t.Type, (SELECT STUFF((SELECT '', '' + t2.Name FROM YourTable t2 WHERE t2.Title = t.Title AND t2.Type = t.Type ORDER BY t2.Name FOR XML PATH('''')),1,2,'''')) AS Names
FROM YourTable t
GROUP BY t.Type, t.Title
) tg
pivot (max(Names) for tg.Type in (' + @collist + ')) p
';
exec sp_executesql @qry;