In this article will present how we can write a Dynamic PIVOT query with an example, where we don’t need to mention the PIVOT columns each unique value, and no need to worry if the PIVOT column gets extra unique values after the initial query.

 

In the Previous Post PIVOT and UNPIVOT in SQL Server explained how PIVOT relational operator can be used to transform column’s distinct values as Columns in the result set by mentioning all the distinct column values in the PIVOT operators PIVOT columns IN clause.

 

This type of PIVOT query is called Static PIVOT query, because if the PIVOT column in the source table gets extra unique values after the initial query then that will not reflect in the PIVOT query result unless it is mentioned in the PIVOT Columns IN clause. Static PIVOT queries are fine as long as we know that the PIVOT column values never change, for instance, if PIVOT column values are MONTH or Day of the Week or hour of the day, etc.

 

To make the above Static PIVOT query dynamic, basically, we have to remove the hardcoded PIVOT column names specified in the PIVOT operators PIVOT columns IN clause. The below query demonstrates this.

Dynamic PIVOT Dynamic Pivot in SQL Server

Leave a Comment