Using the MIN function in the having clause

2019-02-23 07:30发布

问题:

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);

回答1:

How about using ROWNUM?

SELECT *
FROM(SELECT first_name, salary
     FROM Employees
     ORDER BY salary
) WHERE ROWNUM = 1


回答2:

SELECT first_name, salary  as "sal" 
FROM   employees
WHERE  salary =(SELECT MIN(salary) 
                FROM   employees);


回答3:

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;


回答4:

SELECT TOP 1 WITH TIES *
FROM employees
ORDER BY salary ASC


回答5:

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



回答6:

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