具有多个列的子查询

时间:2016-09-10 09:16:41

标签: sql sql-server sql-server-2014

我尝试构建一个包含多个列的子查询。像这样:

--SELF JOIN:
WITH Employees AS
(
    SELECT 
        e.EmployeeID, e.ManagerID, e.Title,
        c.FirstName + ISNULL(' ' + c.MiddleName,'') + ' ' + c.LastName AS EmpName
    FROM 
        Employee AS e
    INNER JOIN 
        Contact AS c ON e.ContactID = c.ContactID
)
SELECT 
    emp.EmployeeID, emp.ManagerID, emp.EmpName, emp.Title AS EmpTitle,
    mgr.EmpName as MgrName, mgr.Title as MgrTitle
FROM 
    Employees AS Emp 
INNER JOIN 
    Employees AS Mgr ON Emp.ManagerID = Mgr.EmployeeID;

--2
WITH Employees AS 
(
    SELECT 
        e.EmployeeID, e.ManagerID, e.Title,
        c.FirstName + ISNULL(' ' + c.MiddleName,'') + ' ' + c.LastName AS EmpName
    FROM 
        Employee AS e
    INNER JOIN 
        Contact AS c ON e.ContactID = c.ContactID
)
SELECT 
    EmployeeID, ManagerID, EmpName, Title
FROM 
    Employees
WHERE 
    EmployeeID IN  (SELECT EmployeeID, er2.MaritalStatus
                    FROM Employees AS e
                    INNER JOIN AdventureWorks2012.HumanResources.Employee AS er2 ON e.ManagerID = er2.BusinessEntityID
                    WHERE er2.MaritalStatus = 'M');

我还要展示MarialStatus。但我不能这样做,因为我得到了错误:

  

当选择列表中只能指定一个表达式时   子查询不是用EXISTS引入的。

但如果我不能在子查询中存在它。所以我的问题是:在子查询中选择多于一列的正确方法是什么?

谢谢

2 个答案:

答案 0 :(得分:1)

您无法在子查询中返回2个值。因此,您必须删除MaritalStatus列。这是你的查询的问题。

USE tempdb;
WITH
Employees AS(
SELECT e.EmployeeID, e.ManagerID,e.Title,
c.FirstName + ISNULL(' ' + c.MiddleName,'') + ' ' + c.LastName AS EmpName
FROM Employee AS e
INNER JOIN Contact AS c
ON e.ContactID = c.ContactID
)
SELECT emp.EmployeeID, emp.ManagerID, emp.EmpName, emp.Title AS EmpTitle,
mgr.EmpName as MgrName, mgr.Title as MgrTitle
FROM Employees AS Emp INNER JOIN Employees AS Mgr
ON Emp.ManagerID = Mgr.EmployeeID;
--2
WITH Employees AS (
SELECT e.EmployeeID, e.ManagerID,e.Title,
c.FirstName + ISNULL(' ' + c.MiddleName,'') + ' ' + c.LastName AS EmpName
FROM Employee AS e
INNER JOIN Contact AS c
ON e.ContactID = c.ContactID)

SELECT e.EmployeeID, e.ManagerID, e.EmpName, e.Title,er2.MaritalStatus
FROM Employees e
INNER JOIN AdventureWorks2012.HumanResources.Employee AS er2 
ON e.ManagerID = er2.BusinessEntityID
WHERE er2.MaritalStatus = 'M');

我认为你不需要子查询,因为如果匹配,INNER JOIN只会给你一个记录。所以从表中做INNER JOIN并将MaritalStatus列放在select子句

答案 1 :(得分:1)

问题似乎出现在您的第二个查询中。 SELECT中没有必要使用第二列。但是,您可以通过删除JOIN

来进一步简化逻辑
SELECT e.EmployeeID, e.ManagerID, e.EmpName, e.Title
FROM Employees e
WHERE e.ManagerID IN (SELECT er2.BusinessEntityID
                      FROM AdventureWorks2012.HumanResources.Employee er2
                      WHERE er2.MaritalStatus = 'M'
                     );