Search code examples
sqlpostgresqlgreatest-n-per-group

Query to display employees with lowest salary from each department


I want to display the lowest earning employees of each department based on salary using min().

I have tables of employees with id, first name, last name, department id, salary and departments, department_id, name department id from 1 to 5.

I am having trouble doing this, I only know how to start SELECT name, surname from employees WHERE...


Solution

  • You would use min() for this. You would use window functions:

    select e.*
    from (select e.*,
                 rank() over (partition by department_id order by salary) as seqnum
          from employees e
         ) e
    where seqnum = 1
    order by department_id;