SQL Server 2008 Pivot没有聚合函数

时间:2013-05-30 21:15:58

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

我有一个表UserRoleTable,它有IDJobIdProjectManagerEngineer列:

**ID     JobId      Engg      Manager**

001    1001       x         Null
002    1002       Null      P
003    1003       Y         Q
004    1004       Z         Null
005    1005       Null      J   

我想要这种格式的结果:

ID     JobId      Name      Role

001    1001       x         Engg
002    1002       P         Manager
003    1003       Y         Engg
003    1003       Q         Manager
004    1004       Z         Engg
005    1005       J         Manager

没有涉及主键或外键。

我应该使用Pivot来实现此功能吗?

1 个答案:

答案 0 :(得分:7)

您可以使用CROSS APPLYVALUES取消隐藏数据:

select id, jobid,
    name,
    role
from UserRoleTable
cross apply
(
    values ('Engg', engg), ('Manager', Manager)
) c (role, name)
where name is not null;

请参阅SQL Fiddle with Demo

或者您可以使用UNPIVOT功能:

select id, jobid, name, role
from UserRoleTable
unpivot
(
  name
  for role in (Engg, Manager)
) unpiv;

请参阅SQL Fiddle with Demo

这是一个UNION解决方案:

  SELECT id, jobid, Engg AS name, 'Engg' AS role
    FROM UserRoleTable
    WHERE Engg IS NOT NULL
  UNION ALL  
  SELECT id, jobid, Manager, 'Manager'
    FROM UserRoleTable
    WHERE Manager IS NOT NULL 
  ORDER BY id, role ;

请参阅SQL Fiddle with Demo