简体   繁体   English

SQl查询以从单行作为多行获取数据

[英]SQl Query to get data from single row as multiple rows

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 现在我想要基于员工ID的输出,如下所示

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. 更重要的是,如上所述,我需要将其作为两个单独的行来获取,并且Role不是表中的一列,根据给定的ID,其值可以是Approver或Owner。

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 一个简单的解决方案是联合: 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 你也可以使用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

try out this 试试这个

SELECT Department_name , Role FROM TableName UNPIVOT (Role for Department_name in (Owner_ID , Approver_ID)) AS Role SELECT Department_name,Role FROM TableName UNPIVOT((Owner_ID,Approver_ID)中Department_name的角色)AS角色

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM