简体   繁体   中英

what is the query to return Name and Salary of employee Having Max Salary

  1. 返回员工姓名和工资的查询是什么

SELECT Name, Salary FROM Minions
WHERE Salary = (SELECT Max(Salary) FROM Minions)

Note that this will return more than one row if there is more than one employee who have the same max salary

select name, salary from (select * from salary_table order by salary desc limit 1)
SELECT FirstName, max(salary)
FROM Employees 
WHERE salary = (
                SELECT max(salary)
                FROM employees
               )
GROUP BY FirstName

working in SQL SERVER 2012

If you are using an oracle database and only want a single "employee" then:

SELECT MAX( name   ) KEEP ( DENSE_RANK LAST ORDER BY salary ASC ) AS name,
       MAX( salary ) KEEP ( DENSE_RANK LAST ORDER BY salary ASC ) AS salary
FROM   Minions;

SQLFIDDLE

(kudos to Neil N for his table name)

  • SQL Server has a similar FIRST_VALUE (or LAST_VALUE ) analytic function.
  • PostgreSQL also supports window functions including LAST_VALUE .
Select e.name, e.salary from employee e where
  not exists (select salary from employee e1 where e.salary < e1.salary)

This will of course return more than one record if there are multiple people with the max salary.

A couple of proprietary solutions

SELECT TOP 1 [WITH ties] Name, Salary
FROM employee
ORDER BY  Salary DESC


SELECT Name, Salary
FROM employee
ORDER BY  Salary DESC
LIMIT 1

And a standard one

WITH E AS
(
    SELECT Name, Salary, 
    ROW_NUMBER() OVER (ORDER BY Salary DESC) RN /*Or RANK() for ties*/
    FROM employee
)
SELECT Name, Salary FROM E WHERE RN=1

These type of queries (grouped operaions) can execute with sub query. Example

select *from emp where sal=(max(sal)from emp)

In case there are multiple rows with the same MAX number then you can just limit the number to desired number like this

SELECT Name, Salary FROM Minions
WHERE Salary = (SELECT Max(Salary) FROM Minions) LIMIT 1

Assuming only one employee has maximum salary

SQL Server:

select top 1 name, salary
from employee
order by salary desc

Oracle:

select name, salary
from employee
order by salary desc
limit 1

Above queries scans the table only once unlike other queries using subqueries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM