Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pivoting on a column without knowing the entire list of values

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?

like image 507
stackoverflowuser Avatar asked Mar 11 '10 00:03

stackoverflowuser


People also ask

How do I create a PivotTable without sums?

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.

How do you pivot a column in Excel?

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.


1 Answers

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;
like image 50
Rob Farley Avatar answered Nov 03 '22 04:11

Rob Farley