有人可以帮助我。
我有一个表结构如下
Department_name | Owner_ID | Approver_ID
-----------------------------------------
Dept 1 | 1234567 | 1234567
现在我希望输出基于员工ID,如下所示
喜欢
select department_name,Role where Owner_ID= '1234567' or Approver_ID = '1234567'
Department_name | Role
-------------------------
Dept 1 | Owner
Dept 1 | Approver
更重要的是,我需要将它作为两个单独的行,如上所示,而Role不是表中的列,它的值将是基于给定ID的Approver或Owner。
我无法弄清楚如何获得这个。 提前谢谢。
答案 0 :(得分:1)
一个简单的解决方案是联盟:http://sqlfiddle.com/#!6/f13c9/5/0
SELECT
Department_name,
'Owner'
FROM test
WHERE Owner_ID = 1234567
UNION ALL
SELECT
Department_name,
'Approver'
FROM test
WHERE Approver_ID = 1234567
答案 1 :(得分:1)
请试试这个..
SELECT Department_name,
CASE WHEN Role = (SELECT Owner_ID FROM Department)
THEN 'Owner' ELSE 'Approver'
END AS Role
FROM Department
UNPIVOT(Role for Column1 in(Owner_ID,Approver_ID)) AS Role
答案 2 :(得分:0)
您也可以使用APPLY运算符
SELECT t.Department_name, o.Role
FROM dbo.YourTable t
CROSS APPLY (
VALUES(CASE WHEN t.Owner_ID = '1234567' THEN 'Owner' END),
(CASE WHEN t.Approver_ID = '1234567' THEN 'Approver' END)
) o(Role)
WHERE o.Role IS NOT NULL
答案 3 :(得分:0)
试试这个
SELECT Department_name,Role FROM TableName UNPIVOT(DepartmentName在(Owner_ID,Approver_ID)中的角色)AS角色