您試圖旋轉您的結果並在列名中包含計數器。由於我假定您不知道可能的列數,所以您需要使用動態SQL來完成此操作。
這應該是接近使用ROW_NUMBER
拿到櫃檯:
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)
可能重複的:http://stackoverflow.com/questions/13103114/tsql-select- values-from-rows-as-columns – JanR