Is it possible to submit a query to PIVOT as a column in SQL Server?

As you know, the syntax is PIVOTas follows:

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

I want to know if it is possible to transfer the request as <column_list>to PIVOT?

In action I want to write

FOR DepartmentName IN (SELECT Name From Department))

instead

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

+3
source share
3 answers

The list INdefines the layout of the results.

It must be known during parsing.

+2
source

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

+1
source

The only way to have dynamic "column_list" is to use dynamic sql. You must create your main query, insert your list of columns into it, and then run it.

SQL Server 2005 basics on an unknown number of columns

+1
source

Source: https://habr.com/ru/post/1735040/


All Articles