3

我的桌子就像

CompanyName | DirectorName
ADS         | Rai
ADS         | Rao
ADS         | Raj
ADS         | Rio
SAS         | Josh
SAS         | John

但我想要这样的结果:

CompanyName | Director1 | Director2 | Director3 | Director4 
ADS         |Rai        |Rao        |Raj        |Rio  
SAS         |Josh       |John       |           |

每个公司的董事姓名数量各不相同。因此,请建议如何根据要求动态形成数据。

4

1 回答 1

4

试试这个:

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

SQL 小提琴演示1

1:感谢@bluefeet

于 2012-11-15T12:46:57.943 回答