How can you pivot rows into columns dynamically using T-SQL?
How can you pivot rows into columns dynamically using T-SQL?
Web Developer
I am a professional .NET developer with over 4 years of hands-on industry experience in designing, developing, and maintaining scalable web applications. I specialize in .NET Core, C#, RESTful APIs, and database-driven systems using SQL Server.
In 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
Yearvalues as columns, with totalAmountas 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.