简体   繁体   中英

How do I select all records having the max value in a column in SQL?

Suppose I have the following Database:

Create table Employee (emp_id int, emp_name varchar(20), staff int);

Insert into Employee values(101,"John", 3);    
Insert into Employee values(102,"Mary", 3);    
Insert into Employee values(103,"Smith",2);    
Insert into Employee values(104,"Bill", 2);    
Insert into Employee values(105,"Kelly", 1);

I want it to select print John and Mary, because they have the highest staff, ie 3. Could anyone please shed some light?

I have tried doing:

select emp_name from Employee having staff = max(staff);

but i keep getting an error!

You can use a subquery that returns the max staff of the table:

select e.* from Employee e
where e.staff = (select max(staff) from Employee)
= (SELECT MAX(staff) FROM Employee) 

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