在不知道整个值列表的情况下在列上进行旋转

时间:2010-03-11 00:24:37

标签: sql-server sql-server-2005 tsql sql-server-2008

我有一张桌子

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等。

如何做到这一点?

1 个答案:

答案 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;