Convert Rows to columns using ‘Pivot’ in SQL Server

'Pivot' in SQL Server

If you are using SQL Server 2014+, then you can use the PIVOT function to transform the data from rows into columns.

It sounds like you will need to use dynamic sql if the weeks are unknown but it is easier to see the correct code using a hard-coded version initially.

If your values are known, then you will hard-code the query:


you would like it to come out as a pivot table, like this:

You need the next code:


Then if you need to generate the week number dynamically, your code will be: