sql查询只返回1个值

时间:2015-12-08 17:05:51

标签: sql-server

AdventureWorks2012数据库 - 我正在尝试从财务部门和工程师部门返回前1或2名emlpoyees,他们工作时间最长。我不能让我的查询返回两者,只有工程展示的结果。有什么建议吗?

SELECT TOP 2 EDH.StartDate, E.BusinessEntityID, D.Name, EDH.EndDate, DATEDIFF(hour,EDH.StartDate, GETDATE()) AS HoursWorked
FROM HumanResources.Employee E
INNER JOIN Person.Person PP ON E.BusinessEntityID = PP.BusinessEntityID
INNER JOIN HumanResources.EmployeeDepartmentHistory EDH ON E.BusinessEntityID = EDH.BusinessEntityID
INNER JOIN HumanResources.Department D ON D.DepartmentID = EDH.DepartmentID
WHERE (D.Name LIKE 'Finance' OR D.Name = 'Engineering')
AND EDH.EndDate IS NULL
GROUP BY D.Name, EDH.StartDate,E.BusinessEntityID,EDH.EndDate
ORDER BY EDH.StartDate ASC

1 个答案:

答案 0 :(得分:0)

您的问题是,来自工程部门的员工恰好已经从财务部门的员工开始。 ORDER BY会影响您的所有记录(两个部门),然后TOP 2值会抓住最近的两名员工,无论是哪个部门。

如果您正在尝试编写一个返回每个部门的第一个员工的查询,那么您将不得不变得更复杂一些。下面是一个示例,它使用ROW_NUMBER()函数按开始日期对每个部门内的员工进行排序,然后将这些记录过滤为仅返回其部门中第一个人员的员工。

SELECT 
    StartDate,
    BusinessEntityID,
    Name,
    EndDate,
    HoursWorked
FROM 
  (
    SELECT 
        EDH.StartDate, 
        E.BusinessEntityID, 
        D.Name, 
        EDH.EndDate, 
        DATEDIFF(hour,EDH.StartDate, GETDATE()) AS HoursWorked,
        ROW_NUMBER() OVER (PARTITION BY D.Name ORDER BY EDH.StartDate) AS RowNumberWithinDepartment
    FROM 
        HumanResources.Employee E
         INNER JOIN 
        Person.Person PP ON E.BusinessEntityID = PP.BusinessEntityID
         INNER JOIN 
        HumanResources.EmployeeDepartmentHistory EDH ON E.BusinessEntityID = EDH.BusinessEntityID
         INNER JOIN 
        HumanResources.Department D ON D.DepartmentID = EDH.DepartmentID
    WHERE 
        (D.Name LIKE 'Finance' OR D.Name = 'Engineering') AND 
        EDH.EndDate IS NULL
    GROUP BY D.Name, EDH.StartDate,E.BusinessEntityID,EDH.EndDate
  ) x 
WHERE RowNumberWithinDepartment = 1
ORDER BY StartDate ASC