Using the MIN function in the having clause

2019-02-23 07:51发布

I want to get the name of the employee who has the minimum salary. Is there a way to do this using only one query? I have given my query below, it doesn't work because the having clause requires a condition. Is there any way to give a condition in the having clause that will retreive the employee name with the minimum salary?

SELECT first_name,min(salary) as "sal"
FROM Employees
GROUP BY first_name 
having min(salary);

6条回答
对你真心纯属浪费
2楼-- · 2019-02-23 08:04

Try this solution, inspired from here:

SELECT e1.first_name, e1.salary AS "sal"
FROM Employees e1
LEFT OUTER JOIN Employees e2
ON (e1.id <> e2.id AND e1.salary > e2.salary)
WHERE e2.id IS NULL;
查看更多
爷的心禁止访问
3楼-- · 2019-02-23 08:08

How about using ROWNUM?

SELECT *
FROM(SELECT first_name, salary
     FROM Employees
     ORDER BY salary
) WHERE ROWNUM = 1
查看更多
在下西门庆
4楼-- · 2019-02-23 08:09
SELECT TOP 1 WITH TIES *
FROM employees
ORDER BY salary ASC
查看更多
ゆ 、 Hurt°
5楼-- · 2019-02-23 08:14

If you need the employee with the lowest salary why don't you use Order By ..

SELECT top 1 first_name,min(salary) as LowestSalary
FROM Employees order by Salary asc
查看更多
【Aperson】
6楼-- · 2019-02-23 08:15

With a single SELECT statement:

SELECT MIN( first_name ) KEEP ( DENSE_RANK FIRST ORDER BY salary ASC, first_name ASC ) AS first_name,
       MIN( salary     ) KEEP ( DENSE_RANK FIRST ORDER BY salary ASC, first_name ASC ) AS salary
FROM   Employees;

SQLFIDDLE

However, if there are multiple people with the same minimum salary then this will only get the one with the name which is first alphabetically.

You can get all the names, but it does require multiple SELECT statements:

SELECT first_name, salary
FROM   Employees
WHERE  salary = ( SELECT MIN(salary) FROM Employees ); 

But having multiple SELECT statements isn't a bad thing.

SQLFIDDLE

查看更多
Deceive 欺骗
7楼-- · 2019-02-23 08:22
SELECT first_name, salary  as "sal" 
FROM   employees
WHERE  salary =(SELECT MIN(salary) 
                FROM   employees);
查看更多
登录 后发表回答