简体   繁体   中英

Select records with maximum value

I have a table that is called: customers .

I'm trying to get the name and the salary of the people who have the maximum salary.

So I have tried this:

SELECT name, salary AS MaxSalary
FROM CUSTOMERS 
GROUP BY salary
HAVING salary = max(salary)

Unfortunately, I got this error:

Column 'CUSTOMERS.name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I know I should add the name column to the group by clause, but I get all the records of the table.

I know that I can do it by:

SELECT name, salary
FROM CUSTOMERS
WHERE salary = (SELECT MAX(salary) FROM CUSTOMERS)

But I want to achieve it by group by and having clauses.

This requirement isn't really suited for a group by and having solution. The easiest way to do so, assuming you're using a modern-insh version of MS SQL Server, is to use the rank window function:

SELECT name, salary
FROM   (SELECT name, salary, RANK() OVER (ORDER BY salary DESC) rk
        FROM   customers) c
WHERE  rk = 1

Mureinik's answer is good with rank, but if you didn't want a windowed function for whatever reason, you can just use a CTE or a subquery.

with mxs as (
  select
    max(salary) max_salary
  from
    customers
)
select
  name
  ,salary
from
  customers cst
  join mxs on mxs.max_salary = cst.salary

There was no need to use group by and having clause there, you know. But if you want to use them then query should be

SELECT name, salary 
FROM CUSTOMERS 
GROUP BY salary 
having salary = (select max(salary) from CUSTOMERS)

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