Skip to content
Advertisement

Rotate rows into columns with column names not coming from the row

I’ve looked at some answers but none of them seem to be applicable to me.

Basically I have this result set:

I just want to convert this to

I know I should probably use PIVOT. But the syntax is just not clear to me.

The order numbers are always two. To make things clearer

Advertisement

Answer

And if you want to use PIVOT then the following works with the data provided:

Reference: https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017

Note: To build each row in the result set the pivot function is grouping by the columns not begin pivoted. Therefore you need an aggregate function on the column that is being pivoted. You won’t notice it in this instance because you have unique rows to start with – but if you had multiple rows with the RowNo and Id you would then find the aggregation comes into play.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement