Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible that we pass a query to PIVOT as column list in SQL Server?

As you know the PIVOT syntax is like below :

FROM table_source
PIVOT ( 
 aggregate_function ( value_column )
 FOR pivot_column
 IN ( <column_list>)
) table_alias

I want to know is it possible that we pass a query as <column_list> to PIVOT?

In action, I want to write

FOR DepartmentName IN (SELECT Name From Department))

instead of

FOR DepartmentName IN ([Production], [Engineering], [Marketing]))

like image 858
masoud ramezani Avatar asked Sep 02 '25 01:09

masoud ramezani


2 Answers

The IN list defines the resultset layout.

It should be known at parse time.

like image 199
Quassnoi Avatar answered Sep 06 '25 17:09

Quassnoi


If I understand you correctly, NO, you can only do that with dynamic sql.

like image 25
Adriaan Stander Avatar answered Sep 06 '25 16:09

Adriaan Stander