Convert Rows to Columns in SQL Server
This article will help to convert values in rows to column/fields name or headers.
This article will helps to convert row values to column/fields, either name or headers using PIVOT operator.
Sometimes we need to generate reports which shows row values as column headers or name. Normally developers use a CASE WHEN statement,
do a cursor or for-loop and generate tables on runtime, or use UNION/UNION ALL etc.. Another way will do the logic on code-behind page.
All these different work rounds can be avoid by using "PIVOT Transformation". Consider a sample: I want to list the Top Contributors of C# Corner.
The output will look like below.
Now, to convert all usernames to columns or fields and show their respective points below. The expected output should looks like below:
There are many different ways available on the web. But using PIVOT is much simpler and faster.
The below following method used is PIVOT with Dynamic Columns to convert rows to columns.
STUFF function inserts a string to another string.
e.g.: SELECT STUFF('Test', 1, 0, '*') and the output will be *Test.
For XML Path is used for concatenating the Strings.From above query, select @columns columns will return output as following..
Relational operator PIVOT definition from msdn:
"PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output,
and performs aggregations where they are required on any remaining column values that are wanted in the final output."
Refer Article Extensions where another sample updated.
Hope this article helps you to convert rows values to columns headers. I will update the article with more complex samples soon.
Download the attachment and test the query. Post comments and rate it. Also, post all the doubts to the forum section.
Thank You !