How can you pivot rows into columns dynamically using T-SQL?
How can you pivot rows into columns dynamically using T-SQL?
137
30-Apr-2025
Updated on 03-May-2025
Khushi Singh
03-May-2025In SQL Server, if you need to turn rows into columns and you don’t know the column headers beforehand—like years, months, or products—dynamic pivoting is the way to go. Unlike regular pivoting where you’d have fixed column names, dynamic pivoting adjusts on the fly, which is perfect for flexible reporting. You can do this using dynamic SQL with the PIVOT operator.
Let’s take a look at an example with a Sales table that has three columns: Region, Year, and Amount. Here's a snapshot of the data:
We want to pivot this data to show
Year
values as columns, with totalAmount
as values, resulting in:To create this dynamically, you can use the following T-SQL:
In this code, we first get the unique years and build a string for the pivot columns. The QUOTENAME function makes sure the column names are correctly formatted, while STRING_AGG combines them for the pivot clause. This way, the script adapts well to any changes in the data, which is great for making dynamic dashboards or reports.