计算最大值数
Counting the Maximum Number of Values
我有一个数据tableEmployees,我想显示在雇佣了最大人数的同一天所有被雇佣的员工。这是我的代码:
select last_name, hire_date, count(*) as "Number of Employees Hired"
from employees
group by last_name, hire_date
where hire_date = max(count(*));
但是,当我 运行 时,此代码显示 "SQL Command Not Properly Ended" 错误。我该如何修复它才能使它 运行 正确?
首先,您应该在 GROUP BY
子句之前使用 WHERE
,其次您应该正确使用聚合函数 (count
),因为在您的情况下 count(*)
不能在 WHERE
子句中进行比较。
您可以在不使用 where 的情况下使用以下方法:(在 MySQL 下测试)
select last_name, hire_date, count(*) as "Number of Employees Hired"
from employees
group by last_name, hire_date
Order by "Number of Employees Hired" desc limit 1
希望这对您有所帮助。干杯。
这可能不是最干净的方法,但我认为可以解决问题:
SELECT last_name,
max_hire.hire_date,
max_hire.cnt
FROM
(SELECT *
FROM
(SELECT hire_date,
COUNT(*) cnt
FROM employees
GROUP BY hire_date
ORDER BY COUNT(*) DESC
)
WHERE rownum = 1
) max_hire
INNER JOIN employees
ON employees.hire_date = max_hire.hire_date
我有一个数据tableEmployees,我想显示在雇佣了最大人数的同一天所有被雇佣的员工。这是我的代码:
select last_name, hire_date, count(*) as "Number of Employees Hired"
from employees
group by last_name, hire_date
where hire_date = max(count(*));
但是,当我 运行 时,此代码显示 "SQL Command Not Properly Ended" 错误。我该如何修复它才能使它 运行 正确?
首先,您应该在 GROUP BY
子句之前使用 WHERE
,其次您应该正确使用聚合函数 (count
),因为在您的情况下 count(*)
不能在 WHERE
子句中进行比较。
您可以在不使用 where 的情况下使用以下方法:(在 MySQL 下测试)
select last_name, hire_date, count(*) as "Number of Employees Hired"
from employees
group by last_name, hire_date
Order by "Number of Employees Hired" desc limit 1
希望这对您有所帮助。干杯。
这可能不是最干净的方法,但我认为可以解决问题:
SELECT last_name,
max_hire.hire_date,
max_hire.cnt
FROM
(SELECT *
FROM
(SELECT hire_date,
COUNT(*) cnt
FROM employees
GROUP BY hire_date
ORDER BY COUNT(*) DESC
)
WHERE rownum = 1
) max_hire
INNER JOIN employees
ON employees.hire_date = max_hire.hire_date