通过对一行值进行分组将行转换为列

时间:2012-11-15 11:32:25

标签: sql sql-server sql-server-2008 pivot

我的表就像

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       |           |

每家公司的董事姓名都有所不同。所以请建议如何根据需求动态形成数据。

1 个答案:

答案 0 :(得分: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 Fiddle Demo1

1:感谢@bluefeet