试试这个:
DECLARE @cols AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);
SELECT @cols = STUFF((SELECT distinct ',' +
QUOTENAME('Director' + CAST(ROW_NUMBER()
OVER(PARTITION BY c.companyname
ORDER BY c.companyname)
AS VARCHAR(10)))
FROM CompaniesDirectors c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)') ,1,1,'');
SET @query = 'SELECT companyname, ' + @cols + ' from
(
SELECT
c.CompanyName,
c.DirectorName,
''Director'' + CAST(ROW_NUMBER()
OVER(PARTITION BY c.companyname
ORDER BY c.companyname)
AS VARCHAR(10)) director_num
FROM CompaniesDirectors c
) x
PIVOT
(
MAX(directorname)
FOR director_num IN (' + @cols + ')
) p ';
EXECUTE(@query);
这应该给你类似的东西:
companyname Director1 Director2 Director3 Director4
AB Foo Bar rr tt
ADS Rai Rao Raj Rio
1:感谢@bluefeet