2013-05-30 39 views
0

我有一個表UserRoleTable,它有列IDJobIdProjectManagerEngineerSQL Server 2008的樞軸不與集合函數

**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嗎?

+2

FYI這是因爲你的列標題更大的逆轉置正在成爲價值。 – AaronLS

回答

7

您可以使用CROSS APPLYVALUES到unpivot的數據:

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

+0

@ user2438237'PIVOT'是兩個答案中更優雅的。我會用你的數據集嘗試它們,看看哪個具有更好的性能特徵。 – swasheck

+0

@bluefeet:很多。它運行得非常好。我不太瞭解cross apply,pivot,unpivot命令。好像我必須學習它們。不管怎麼說,多謝拉。 – user2438237

+0

@ user2438237 ......更不用說落後的案例邏輯了。 – swasheck