Using the MIN function in the having clause

后端 未结 7 1077
感动是毒
感动是毒 2021-01-18 07:06

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

相关标签:
7条回答
  • 2021-01-18 07:35

    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

    0 讨论(0)
  • 2021-01-18 07:40
    SELECT first_name, salary  as "sal" 
    FROM   employees
    WHERE  salary =(SELECT MIN(salary) 
                    FROM   employees);
    
    0 讨论(0)
  • 2021-01-18 07:47

    How about using ROWNUM?

    SELECT *
    FROM(SELECT first_name, salary
         FROM Employees
         ORDER BY salary
    ) WHERE ROWNUM = 1
    
    0 讨论(0)
  • 2021-01-18 07:49

    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;
    
    0 讨论(0)
  • 2021-01-18 07:52

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

    0 讨论(0)
  • 2021-01-18 07:53
    SELECT TOP 1 WITH TIES *
    FROM employees
    ORDER BY salary ASC
    
    0 讨论(0)
提交回复
热议问题