views:

35

answers:

1

I have a table

Title            Name             Type
------------------------------------------------
T1               A                Primary
T1               B                Primary
T2               B                Primary
T2               C                Secondary
T2               D                Secondary

I need the output to be

Title            Primary          Secondary
------------------------------------------------
T1               A, B             NULL/Blank
T2               B                C, D

[Name] column in the original table can have any value. i.e. later there could be E, F, G etc.

How can this be done?

+2  A: 

Then you need dynamic SQL. Consider something like this for generating the list of columns:

DECLARE @collist nvarchar(max);
SELECT @collist = STUFF((SELECT ', ' + quotename(Type) FROM YourTable GROUP BY Type FOR XML PATH('')), 1, 2, '');

Now you can use @collist to help construct the query you want, which you then run using sp_executesql

Like this:

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;
Rob Farley
I am just getting into understanding PIVOT. I did run the query which gave me the output as [Primary], [Primary], [Primary], [Secondary], [Secondary]. But how can PIVOT be applied for the desired output?
stackoverflowuser
Please post the complete output in case I can help.
Will Marcouiller
@Will: the output in my comment is the completed ouptput after running @collist mentioned in the answer by Rob Farley. And the desired output mentioned in the question is the complete output desired. Hope this clarifies.
stackoverflowuser
Ah - I missed a GROUP BY.
Rob Farley
@stackoverflowuser: I'm sorry, I thought you were asking about how to use PIVOT for the DESIRED output from there. My bad! =)
Will Marcouiller
@Rob: Thanks a ton !!
stackoverflowuser