我有一个表UserRoleTable
,它有ID
,JobId
,ProjectManager
,Engineer
列:
**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
来实现此功能吗?
答案 0 :(得分:7)
您可以使用CROSS APPLY
和VALUES
取消隐藏数据:
select id, jobid,
name,
role
from UserRoleTable
cross apply
(
values ('Engg', engg), ('Manager', Manager)
) c (role, name)
where name is not null;
或者您可以使用UNPIVOT
功能:
select id, jobid, name, role
from UserRoleTable
unpivot
(
name
for role in (Engg, Manager)
) unpiv;
这是一个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 ;