[英]Sql server: Join two tables and select multiple column values with subquery
Table OpenPO
表
OpenPO
Shopping_Cart_No ![]() |
Goods_Recipient_Emp_ID ![]() |
accassgnmtownerid ![]() |
---|---|---|
1001958413 ![]() |
160213 ![]() |
65658 ![]() |
1001661570 ![]() |
61875 ![]() |
61855 ![]() |
Table Employee
表
Employee
employee_number![]() |
Email![]() |
---|---|
160213 ![]() |
Quentin_Walker@gmail.com ![]() |
61875 ![]() |
Mihaela_Balseanu@gmail.com ![]() |
65658 ![]() |
siva@gmail.com ![]() |
61855 ![]() |
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 ![]() |
accassgnmtownerid ![]() |
accassgnmtownerid_Email ![]() |
---|---|---|---|
Quentin_Walker@gmail.com ![]() |
160213 ![]() |
65658 ![]() |
siva@gmail.com ![]() |
Mihaela_Balseanu@gmail.com ![]() |
61875 ![]() |
61855 ![]() |
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.