-3

我在 SQL Server 2008 中创建了以下查询

SELECT dimUser.EmpFName, dimUser.EmpLName, dimUser.EmpStartDt, dimUser.MgrEmpFullName1, 
    dimUser.PrimaryJobName, dimUser.PrimaryOrgName, Org.Org_Name
FROM dimUser 
INNER JOIN tblEmpOrg AS fact 
  ON dimUser.ID = fact.EmpOrg_EmpFK 
INNER JOIN Org 
  ON fact.EmpOrg_OrgFK = Org.Org_PK

数据产生多行,因为每个用户有许多不同的组织名称。

Employee Name  Manager Name          Org_Name
Neil Jones     Elizabeth O'Donnell   USA 
Neil Jones     Elizabeth O'Donnell   AFG 
Neil Jones     Elizabeth O'Donnell   USA REG A

如何旋转此查询以为不同的组织生成多个列。IE 组织 1、组织 2、组织 3 等。

Employee Name  Manager Name         Org_NAME 1  Org_Name 2  Org_Name 3
Neil Jones     Elizabeth O'Donnell  USA         AFG         USA REG A
4

1 回答 1

6

您可以使用该PIVOT函数来转换数据。但是,您将希望向row_number()每个员工申请以帮助将行数据转换为列。

如果每个员工都有已知数量的值,则可以对查询进行硬编码,如下所示:

select [Employee Name],
  [Manager Name],
  Org_Name_1, 
  Org_Name_2, 
  Org_Name_3
from
(
  select [Employee Name], [Manager Name], [Org_Name],
    'Org_Name_'+cast(row_number() over(partition by [Employee Name] order by [Employee Name]) as varchar(50)) rn
  from yourtable
) src
pivot
(
  max([Org_Name])
  for rn in (Org_Name_1, Org_Name_2, Org_Name_3)
) piv;

请参阅带有演示的 SQL Fiddle

但是,如果org_name每个员工的值数量未知,则需要使用动态 SQL:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(rn) 
                    from
                    (
                      select 'Org_Name_'+cast(row_number() over(partition by [Employee Name] order by [Employee Name]) as varchar(50)) rn
                      from yourtable
                    ) t
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT [Employee Name], [Manager Name],' + @cols + ' from 
             (
                select [Employee Name], [Manager Name], [Org_Name],
                  ''Org_Name_''+cast(row_number() over(partition by [Employee Name] order by [Employee Name]) as varchar(50)) rn
                from yourtable
            ) x
            pivot 
            (
                max(Org_Name)
                for rn in (' + @cols + ')
            ) p '

execute(@query)

请参阅带有演示的 SQL Fiddle

两者都生成结果:

| EMPLOYEE NAME |        MANAGER NAME | ORG_NAME_1 | ORG_NAME_2 | ORG_NAME_3 |
------------------------------------------------------------------------------
|    Neil Jones | Elizabeth O'Donnell |        USA |        AFG |  USA REG A |

注意:yourtable用您的查询替换

于 2013-02-27T11:31:40.667 回答