This can be accomplished using the PIVOT
function. The GROUP BY
will work because you have an indicator that makes each of the rows distinct. For your data the indicator is the rowNumber
column.
If you have a set number of columns, then you will want to hard-code them using a static pivot. The code will be similar to this following:
select [1], [2], [3]
from
(
select colNumber, RowNumber, CellData
from yourtable
) src
pivot
(
max(CellData)
for colnumber in ([1], [2], [3])
) piv;
See SQL Fiddle with Demo.
In your case, you stated that you will have a unknown number of columns. If that is your situation then you will need to use dynamic sql to build the list of columns to pivot. I demonstrated the static version because it makes it easier to convert the code to dynamic SQL.
The key to the dynamic sql version is getting the list of columns which is done by querying your table and creating a string of the column names. This is done using FOR XML PATH
:
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(colNumber)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
This list is then added into the query string that you generate and the final code is then:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(colNumber)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ' + @cols + '
from
(
select colNumber, rowNumber, CellData
from yourtable
) x
pivot
(
min(CellData)
for colNumber in (' + @cols + ')
) p '
execute(@query)
See SQL Fiddle with Demo.
Both give the result:
| 1 | 2 | 3 |
-----------------------------
| Orange | Apple | Banana |
| Grape | Corn | Lemon |
| Tomato | Lettuce | Onion |