如何使用INNER JOIN将两个字段合并为单个字段

时间:2013-02-06 11:02:53

标签: sql sql-server-2008

我有两张桌子。

**EmployeeInfo**
   EmployeeName varchar(50)
   EmailAddress varchar(100)
   BranchID     int

**BranchInfo**
   BranchID  int
   opMgr     varchar(100)
   BranchMgr varchar(100)

我想要一个存储过程,如果我将电子邮件地址作为参数传递,它应该将branchinfo表中的OpMgr和BranchMgr列显示到EmployeeInfo的相关分支的单个列中。我试着写下面但没有运气,因为我得到多部分错误。

SELECT  BranchInfo.OpMgr FROM  EmployeesInfo 
UNION
SELECT BranchInfo.BranchMgr FROM EmployeesInfo 
INNER JOIN BranchInfo ON EmployeesInfo.BranchID = BranchInfo.BranchID
WHERE AND EMPLOYEESINFO.EMAILADDRESS='john.d@mydomain.com'

4 个答案:

答案 0 :(得分:2)

试试这个:

SELECT
    E.EmployeeName,
    E.EmailAddress,
    B.BranchID,
    B.BranchMgr + ' ' + B.opMgr ColName
FROM EmployeesInfo E
    INNER JOIN BranchInfo B
        ON E.BranchID = B.BranchID
WHERE E.EMAILADDRESS='john.d@mydomain.com'

答案 1 :(得分:1)

你可以JOIN喜欢这个

SELECT b.opMgr + b.BranchMgr as Branch
FROM EmployeeInfo e
JOIN BranchInfo b ON b.BranchID = BranchID
WHERE e.EMAILADDRESS='john.d@mydomain.com'

答案 2 :(得分:1)

  

它应该显示来自branchinfo表的OpMgr和BranchMgr列   进入EmployeeInfo相关分支的单列

DECLARE @opMgr VARCHAR(100), @BranchMgr VARCHAR(100)

SELECT @opMgr  = b.opMgr, @BranchMgr =  b.BranchMgr
FROM EmployeeInfo e
JOIN BranchInfo b ON e.BranchID = b.BranchID
WHERE e.EMAILADDRESS='john.d@mydomain.com'

SELECT details 
FROM ( VALUES (@opMgr),(@BranchMgr)) 
AS t(details) 

答案 3 :(得分:0)

试试这个,

SELECT BranchInfo.OpMgr, BranchInfo.BranchMgr
  FROM EmployeesInfo
 INNER JOIN BranchInfo ON EmployeesInfo.BranchID = BranchInfo.BranchID
 WHERE AND EMPLOYEESINFO.EMAILADDRESS = 'john.d@mydomain.com'