Reputation: 2489
When I run a SQL query which returns one column with variable number of rows returned, I'd like to transform each of the row into column VALUE (I don't mind what the column header/titles are).
E.g.
Column1
-------
a
b
c
d
e
I want a script which will transform the above into a table like:
Col1 Col2 Col3 Col4 Col5
------------------------
a b c d e
(Note that I do not care for the column names).
I know I cannot user PIVOT as row numbers are not fixed (they are based on a SQL query).
Any ideas?
Thanks!
Upvotes: 4
Views: 1897
Reputation: 62841
You're trying to pivot your results and include a counter in your column name. Since I'm presuming you don't know the potential number of columns, you'll need to use Dynamic SQL to accomplish this.
This should be close using ROW_NUMBER
to get the counter:
declare @cols AS NVARCHAR(MAX),
@colswithalias AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
set @colswithalias = STUFF((SELECT distinct ',' + QUOTENAME(col1)
+ ' AS Col'
+ CAST(ROW_NUMBER() OVER (ORDER BY col1) as varchar(10))
FROM yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @cols = STUFF((SELECT distinct ',' + QUOTENAME(col1)
FROM yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ' + @colswithalias + '
from
(
select col1 rn, col1
from yourtable
) x
pivot
(
max(rn)
for col1 in (' + @cols + ')
) p '
execute(@query)
Upvotes: 3