Mat Richardson
Mat Richardson

Reputation: 3606

TSQL - using IN with PIVOT

Quick question that's bugging me.

When using PIVOT in T-SQL, can the 'FOR..IN' portion reference a table rather than a defined list of values?

Example, instead of something like:-

PIVOT (Count(widgets) For Team IN ([Dave],[Peter],[John]....etc))

Could you do something like:-

PIVOT (Count(widgets) for Team IN (SELECT TeamLeader FROM Teams))

I can find no reference to confirm whether or not this is possible.

Upvotes: 2

Views: 72

Answers (1)

Mahmoud Gamal
Mahmoud Gamal

Reputation: 79949

No, this is not possible.

The PIVOT operator syntax dictates that these values is entered as a list:

...

IN ( [first pivoted column], 

     [second pivoted column],

...
...

     [last pivoted column])

But you can do this dynamically, something like:

DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);


select @cols = STUFF((SELECT distinct ',' +
                        QUOTENAME(Teamleader)
                      FROM Teams
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)') 
                        , 1, 1, '');


SELECT @query = ' SELECT ' + @cols +
                ' FROM AnotherTable a
                  PIVOT 
                  (
                     Count(widgets) For Team IN (' + @cols + ')' +
                  ') p';
execute(@query);

Upvotes: 2

Related Questions