menu

arrow_back Mysql: how to choose the top 5 from the groups?

by
1 vote
There is a table:
id,name,otdel,money
-----------------
1,alex,it,1000
2,anna,callcenter,2000
3,anton,it,3000

Etc.
We need to select from each department the top 5 employees with the highest salary.
For one group I can make a query select * from users group by otdel ordeer by money asc limit 3 or something like that.

Write a request with an explanation, because I have seen solutions of such problems on the Internet, but I can't make sense of it.

3 Answers

by
0 votes
Somehow, apparently:
select u.* from users as u
where u.id in (select top 5 id from users as u1 where u1.otdel=u.otdel order by u1.money desc)
order by u.otdel, u.money desc

2 Comments

NOOOOOO
romy4 Why, indeed?
I can't test it now, but the query should return the top 5 salaries in each department. This is how I understood the question. Of course it will not work fast, but if the table is not large, then why not.
by
0 votes
I need to select the top 5 employees with the highest salaries in one query from all departments.

1 comment

Use grouping by department
by
0 votes
So you have a ready request

1 comment

And about "I haven't seen it on the Internet" don't lie.