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?
Inside the Pivot Column dialog, select the column with the values that will populate the new columns to be created. In this case "Time" but could be any field type, including text. In the Advanced Options part, select "Don´t Aggregate" so the values will displayed without any modification.
Select the column that you want to pivot. In the example, select Position. This column's unique values become the new columns and column headers. Select Transform > Pivot Column.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With