如何在SQL查询中有多个where子句

时间:2015-11-24 22:42:15

标签: sql join sql-server-2005

在以下查询中,我试图使用'专门设置管理员名称。子查询。我只使用这个子查询,因为我不知道如何为' ManagerID'

指定另一个where子句

我知道连接应该用来代替这些查询,因为它们是逐行操作而不是作为一组操作,但我没有看到另一种方法。目前这个查询不会执行,因为我得到了着名的"子查询返回了多行"任何帮助将不胜感激。

SELECT hrdh.StartDate
    ,hrdh.PositionTitle
    ,HumanResources.Department.NAME
    ,HumanResources.Employee.EmployeeNumber
    ,HumanResources.Employee.Classification
    ,HumanResources.Employee.STATUS
    ,HumanResources.Employee.ManagerID AS ManagerID
    ,Person.Contact.FirstName
    ,Person.Contact.LastName
    ,Person.Contact.SIN
    ,Person.Contact.DateOfBirth
    ,Person.Contact.PhoneNumber
    ,Person.Contact.EmailAddress
    ,Person.Contact.AddressLine1
    ,Person.Contact.AddressLine2
    ,Person.Contact.PostalCode
    ,Person.Contact.City
    ,Person.Contact.Province
    ,(
        SELECT (Person.Contact.FirstName + ' ' + Person.Contact.LastName) AS manager
        FROM Person.Contact
        INNER JOIN HumanResources.Employee 
                ON Person.Contact.ContactID = HumanResources.Employee.ContactID
        WHERE HumanResources.Employee.ManagerID = ManagerID
        ) AS manager
FROM HumanResources.EmployeeDepartmentHistory hrdh
    ,HumanResources.Employee
    ,Person.Contact
    ,HumanResources.Department
WHERE hrdh.EmpID = @empID

1 个答案:

答案 0 :(得分:0)

您需要在所有表之间添加适当的连接条件。下面只是查询的近似值,因为我不知道表格结构或关键列,但它只是想知道如何完成它。

SELECT 
   hrdh.StartDate, hrdh.PositionTitle, d.Name,
   e.EmployeeNumber, e.Classification, e.Status,
   e.ManagerID AS ManagerID, c1.FirstName, c1.LastName, c1.SIN,
   c1.DateOfBirth, c1.PhoneNumber, c1.EmailAddress, c1.AddressLine1,
   c1.AddressLine2, c1.PostalCode, c1.City, c1.Province,
   (c2.FirstName+ ' ' + c2.LastName) AS manager
FROM 
    HumanResources.EmployeeDepartmentHistory hrdh 
    join HumanResources.Employee e on hrdh.keycolumn = e.keycolumn
    join Person.Contact c1 on e.ContactID = c1.ContactID
    join Person.Contact c2 on e.ManagerID = c2.ContactID
    join HumanResources.Department d on d.keycolumn = e.keycolumn
WHERE 
    hrdh.EmpID = @empID