SQL查询 - 不确定如何修复逻辑错误

时间:2016-10-29 13:33:03

标签: sql sql-server where

编辑:对不起!我正在使用Microsoft SQL Server。

为了澄清,您可以拥有一个名为“x”的部门,其中包含一个工作列表,一个名为“y”的部门,其中包含不同的工作列表等。

我还需要使用> = ALL代替TOP 1或MAX,因为如果需要,我需要它返回多个值(如果job1有20名员工,job2有20名员工,他们都是最大值,他们应该都返回)。

在我的查询中,我正在努力找到最常见的职位标题和在此职位下工作的员工人数,这是在“研究与开发”部门下。我写的查询包含连接,以便能够返回必要的数据。

我遇到的问题是WHERE语句。 HAVING COUNT(JobTitle)> = ALL正在寻找在工作中工作的最多员工,但问题是我的WHERE声明说部门必须是'研发',但是工作量最大的工作员工来自不同的部门,因此输出只产生列名而不产生其他任何内容。

我想重做查询,以便返回来自研发部门的员工人数最多的工作。

我知道这可能很简单,我是个菜鸟:3非常感谢你的帮助!

SELECT JobTitle, COUNT(JobTitle) AS JobTitleCount, Department
FROM HumanResources.Employee AS EMP JOIN 
     HumanResources.EmployeeDepartmentHistory AS HIST
     ON EMP.BusinessEntityID = HIST.BusinessEntityID JOIN
     HumanResources.Department AS DEPT
     ON HIST.DepartmentID = DEPT.DepartmentID
WHERE Department = 'Research and Development'
GROUP BY JobTitle, Department
HAVING COUNT(JobTitle) >= ALL (
  SELECT COUNT(JobTitle) FROM HumanResources.Employee
  GROUP BY JobTitle 
)

2 个答案:

答案 0 :(得分:1)

如果您只想要一行,那么典型的方法是:

SELECT JobTitle, COUNT(*) AS JobTitleCount
FROM HumanResources.Employee AS EMP JOIN 
     HumanResources.EmployeeDepartmentHistory AS HIST
     ON EMP.BusinessEntityID = HIST.BusinessEntityID JOIN
     HumanResources.Department AS DEPT
     ON HIST.DepartmentID = DEPT.DepartmentID
WHERE Department = 'Research and Development'
GROUP BY JobTitle
ORDER BY  COUNT(*) DESC
FETCH FIRST 1 ROW ONLY;

虽然FETCH FIRST 1 ROW ONLY是ANSI标准,但有些数据库会将其拼写为LIMIT甚至SELECT TOP (1)

请注意,我从DEPARTMENTSELECT中删除了GROUP BY。这似乎是多余的。

而且,如果我不得不猜测,由于历史表,您的查询会夸大结果。如果是这种情况,请询问另一个问题,并提供样本数据和所需结果。

编辑:

在SQL Server中,我建议使用窗口函数。要获得一个最高职位:

SELECT JobTitle, JobTitleCount
FROM (SELECT JobTitle, COUNT(*) AS JobTitleCount,
             ROW_NUMBER() OVER (ORDER BY COUNT(*) DESC) as seqnum
      FROM HumanResources.Employee AS EMP JOIN 
           HumanResources.EmployeeDepartmentHistory AS HIST
           ON EMP.BusinessEntityID = HIST.BusinessEntityID JOIN
           HumanResources.Department AS DEPT
           ON HIST.DepartmentID = DEPT.DepartmentID
      WHERE Department = 'Research and Development'
      GROUP BY JobTitle
     ) j
WHERE seqnum = 1;

要获取所有此类标题,如果有重复项,请使用RANK()DENSE_RANK()代替ROW_NUMBER()

答案 1 :(得分:0)

with employee_counts as (
    select
        hist.DepartmentID, emp.JobTitle, count(*) as cnt,
        case when dept.Department = 'Research and Development' then 1 else 0 end as is_rd,
    from HumanResources.Employee as emp
         inner join HumanResources.EmployeeDepartmentHistory as hist
             on hist.BusinessEntityID = emp.BusinessEntityID
         inner join HumanResources.Department as dept
             on dept.DepartmentID = hist.DepartmentID
    group by
        hist.DepartmentID, emp.JobTitle
)
select * from employee_counts
where is_rd = 1 and cnt = (
    select max(cnt) from employee_counts
    /* where is_rd = 1 */ -- ??
);