简体   繁体   English

Sql server:连接两个表并使用子查询选择多个列值

[英]Sql server: Join two tables and select multiple column values with subquery

Table OpenPOOpenPO

Shopping_Cart_No Shopping_Cart_No Goods_Recipient_Emp_ID Goods_Recipient_Emp_ID accassgnmtownerid accassgnmtownerid
1001958413 1001958413 160213 160213 65658 65658
1001661570 1001661570 61875 61875 61855 61855

Table EmployeeEmployee

employee_number员工编号 Email电子邮件
160213 160213 Quentin_Walker@gmail.com Quentin_Walker@gmail.com
61875 61875 Mihaela_Balseanu@gmail.com Mihaela_Balseanu@gmail.com
65658 65658 siva@gmail.com siva@gmail.com
61855 61855 mohan@gmail.com mohan@gmail.com

I have these two tables, both are linked by the employee_number column.我有这两个表,都由employee_number列链接。

I want to display data as shown below .我想显示如下所示的数据。

Expected result预期结果

Goods_Recipient_Email货物_收件人_电子邮件 Goods_Recipient_Emp_ID Goods_Recipient_Emp_ID accassgnmtownerid accassgnmtownerid accassgnmtownerid_Email accassgnmtownerid_Email
Quentin_Walker@gmail.com Quentin_Walker@gmail.com 160213 160213 65658 65658 siva@gmail.com siva@gmail.com
Mihaela_Balseanu@gmail.com Mihaela_Balseanu@gmail.com 61875 61875 61855 61855 mohan@gmail.com mohan@gmail.com

Tried with left join and able to compare and select only one email column Goods_Recipient_Emp_ID or op.accassgnmtownerid尝试使用左连接并能够比较并仅选择一个电子邮件列 Goods_Recipient_Emp_ID 或 op.accassgnmtownerid

SELECT 
    op.Goods_Recipient_Emp_ID, op.accassgnmtownerid, 
    te.Email AS accassgnmtownerid_Email
FROM 
    OpenPO op
LEFT JOIN 
    Employee te ON te.Employee_Number = op.Goods_Recipient_Emp_ID  

Tried with subquery for accassgnmtownerid_Email , but it didn't work out.尝试使用accassgnmtownerid_Email的子查询,但没有成功。

Can we apply subquery for accassgnmtownerid_Email or is there any other solution?我们可以为accassgnmtownerid_Email应用子查询还是有其他解决方案?

You need to join the table employee twice, using two different aliases.您需要使用两个不同的别名加入表employee两次。

For example:例如:

select
  r.email as Goods_Recipient_Email,
  o.Goods_Recipient_Emp_ID,
  o.accassgnmtownerid,
  a.email as accassgnmtownerid_Email
from openpo o
join employee r on r.employee_number = o.Goods_Recipient_Emp_ID
join employee a on a.employee_number = o.accassgnmtownerid

Other than joining the tables for each Email, you can also use a correlated subquery for each, such as除了加入每个电子邮件的表之外,您还可以为每个电子邮件使用相关的子查询,例如

select 
  (select Email from Employee e where e.employee_number = po.Goods_Recipient_Emp_ID) Goods_Recipient_Email,
  po.Goods_Recipient_Emp_ID,
  po.accassgnmtownerid,
  (select Email from Employee e where e.employee_number = po.accassgnmtownerid) accassgnmtownerid_Email
from OpenPO po;

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

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