Can someone help me with this.
I have a table structure as follows
Department_name | Owner_ID | Approver_ID
-----------------------------------------
Dept 1 | 1234567 | 1234567
Now I want the output based on the employee ID as follows
like
select department_name,Role where Owner_ID= '1234567' or Approver_ID = '1234567'
Department_name | Role
-------------------------
Dept 1 | Owner
Dept 1 | Approver
More importantly, I need to get it as two separate rows as shown above and Role is not a column in the table its value wil be either Approver or Owner based on given ID.
I am unable to figure out how to get this. Thanks in advance.
A simple solution would be a union: 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
Please Try This..
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
Also you can use APPLY operator
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
try out this
SELECT Department_name , Role FROM TableName UNPIVOT (Role for Department_name in (Owner_ID , Approver_ID)) AS Role
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.