I have a table with four columns item_id, color, size, weight, I want to show my table rows into one row like item1,color1,size1,weight1,item2,color2,...........,item4,color4,size4,weight4 ...
Following is my table
+---------+--------+--------+--------+
| item_id | color | size | weight |
+---------+--------+--------+--------+
| 1 | blue | large | 65 |
| 2 | orange | large | 57 |
| 3 | red | small | 12 |
| 4 | violet | medium | 34 |
My desired result will be
+---------+--------+--------+--------++---------+--------+--------+
| item_id1| color1| size1 | weight1| item_id2 | color2 | size2 | weight2 |....
+---------+--------+--------+--------+---------+--------+--------+---------------
| 1 | blue | large| 65 | 2 | orange | large | 57 |...
+---------+--------+--------+--------+ +---------+--------+--------+--------+
Thanks in advance.
If you want to do it programmatically and you don't know the number of rows try this :
In order to get this result, you will need to do a few things:
Since you are using SQL Server 2005+ you can use CROSS APPLY to unpivot the data, this process takes your multiple columns of
item_id
,color
,size
andweight
and converts them into multiple rows:See SQL Fiddle with Demo. This gives a result:
As you can see from the result you now have multiple rows in based off your original data. The
COL
values are the values that you will use to PIVOT. The full dynamic SQL code will be similar to the following:See SQL Fiddle with Demo. The final result is: