Paste this into a new question or an answer at dba.stackexchange.com:
<!-- --> > Create table If Not Exists Employee (Id int, Name varchar(255), Salary int, DepartmentId int); > > <pre> > ✓ > </pre> <!-- --> > Create table If Not Exists Department (Id int, Name varchar(255)); > > <pre> > ✓ > </pre> <!-- --> > insert into Employee (Id, Name, Salary, DepartmentId) values ('1', 'Joe', '70000', '1'); > > <pre> > ✓ > </pre> <!-- --> > insert into Employee (Id, Name, Salary, DepartmentId) values ('2', 'Henry', '80000', '2'); > > <pre> > ✓ > </pre> <!-- --> > insert into Employee (Id, Name, Salary, DepartmentId) values ('3', 'Sam', '60000', '2'); > > <pre> > ✓ > </pre> <!-- --> > insert into Employee (Id, Name, Salary, DepartmentId) values ('4', 'Max', '90000', '1'); > > <pre> > ✓ > </pre> <!-- --> > insert into Department (Id, Name) values ('1', 'IT'); > > <pre> > ✓ > </pre> <!-- --> > insert into Department (Id, Name) values ('2', 'Sales'); > > <pre> > ✓ > </pre> <!-- --> > SELECT * FROM > ( > SELECT d.Name as Department, e.Name as Employee, Salary, > DENSE_RANK() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC) rank > FROM Employee e JOIN Department d ON e.DepartmentId = d.id > ) t > WHERE rank <= 3 > ORDER BY Department, rank; > > <pre> > Department | Employee | Salary | rank > :--------- | :------- | -----: | ---: > IT | Max | 90000 | 1 > IT | Joe | 70000 | 2 > Sales | Henry | 80000 | 1 > Sales | Sam | 60000 | 2 > </pre> *db<>fiddle [here](https://dbfiddle.uk/?rdbms=mariadb_10.2&fiddle=cc9082f8d09b48dc7f374456ef817a73)*
back to fiddle