I have scenario where I need to change the present data to required one.
Below is the data
ColumnA ColumnB ColumnC
P Q R
S T U
V W X
Required Format is
ColumnA1 ColumnB1 ColumnC1 ColumnA2 ColumnB2 ColumnC2 ColumnA3 ColumnB3 ColumnC3
P Q R S T U V W x
Please help me on this.
There are a few ways that you can get the result all of them involve using
row_number
to generate a sequence for each row of your data.You can use an aggregate function with a CASE expression:
See SQL Fiddle with Demo.
You can use the PIVOT function, but you will want to unpivot your 3 columns of data first, then apply the PIVOT. The unpivot process converts your 3 columns of data into multiple rows. You can use the UNPIVOT function or CROSS APPLY to perform this:
See SQL Fiddle with Demo. The above two versions work great if you have a limited number or known values, but if you will have an unknown number, then you will have to look at using dynamic SQL to get the final result:
See SQL Fiddle with Demo. All versions will give a result: