我需要将这两个查询的结果合并到一个语句中

I need the results from these two queries to be combined into one statement

设置是联系人table、员工table和Employee_contacttable具有多对多关系。我想知道如何将这两个查询合并为一个组合结果集。

SELECT FirstName, LastName, (ContactNumber) AS Home  
FROM Employees AS E
JOIN Employees_Contacts AS EC ON E.EmployeeID = EC.EmployeeID
JOIN Contacts AS C on EC.ContactID = C.ContactID
WHERE ContactType = 'Home Phone'

SELECT FirstName, LastName, (ContactNumber) AS Fax
FROM Employees AS E
JOIN Employees_Contacts AS EC ON E.EmployeeID = EC.EmployeeID
JOIN Contacts AS C on EC.ContactID = C.ContactID
WHERE ContactType = 'Home Fax';

一种选择是使用条件聚合:

SELECT FirstName, LastName,
   MAX(CASE WHEN ContactType = 'Home Phone' THEN ContactNumber END) AS Home,
   MAX(CASE WHEN ContactType = 'Home Fax' THEN ContactNumber END) AS Fax
FROM Employees AS E
    JOIN Employees_Contacts AS EC ON E.EmployeeID = EC.EmployeeID
    JOIN Contacts AS C on EC.ContactID = C.ContactID
WHERE ContactType IN ('Home Phone','Home Fax')
GROUP BY FirstName, LastName

使用案例语句

SELECT FirstName, LastName, 
    CASE
        WHEN ContactType = 'Home Phone' then ContactNumber
        ELSE NULL
    END AS Home,
    CASE
        WHEN ContactType = 'Home Fax' then ContactNumber
        ELSE NULL
    END AS Fax
FROM Employees AS E
JOIN Employees_Contacts AS EC ON E.EmployeeID = EC.EmployeeID
JOIN Contacts AS C on EC.ContactID = C.ContactID

取决于您期望什么样的结果。这 returns 所有拥有第一部 HomePhone 和 HomeFax(如果有)的员工:

SELECT FirstName, LastName,
   (select top 1 ContactNumber from Employees_Contacts AS EC 
                JOIN Contacts AS C on EC.ContactID = C.ContactID 
                where E.EmployeeID = EC.EmployeeID 
                and EC.ContactType = 'Home Phone') as HomePhone,
   (select top 1 ContactNumber from Employees_Contacts AS EC
                JOIN Contacts AS C on EC.ContactID = C.ContactID 
                where E.EmployeeID = EC.EmployeeID 
                and EC.ContactType = 'Home Fax') as Fax
FROM Employees AS E

您的查询返回所有电话和传真。