我在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
如何透视此查询以为不同的组织生成多个列。 I.E. Org 1,Org 2,Org 3等。
Employee Name Manager Name Org_NAME 1 Org_Name 2 Org_Name 3
Neil Jones Elizabeth O'Donnell USA AFG USA REG A
答案 0 :(得分: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;
但是,如果每位员工的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)
两者都生成结果:
| EMPLOYEE NAME | MANAGER NAME | ORG_NAME_1 | ORG_NAME_2 | ORG_NAME_3 |
------------------------------------------------------------------------------
| Neil Jones | Elizabeth O'Donnell | USA | AFG | USA REG A |
注意:将yourtable
替换为您的查询