Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL display maximum 2 employees hired the latest in 2021 per department

A SQL Server database has 2 tables:

  • Department: Id
  • Employee: Id, Department, Employee_Name, Date_Hired

I wanted to display maximum 2 employees hired the latest in 2021 per department

For example

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The output should be

I have this SQL:

SELECT e.* 
FROM Employee e
WHERE e.Date_Hired IN (SELECT e.Date_Hired
                      FROM Employee e
                      WHERE YEAR(e.Date_Hired) = 2021)
ORDER BY e.Date_Hired DESC

But it is displaying all 3 items from department 1.

Thanks in advance!

>Solution :

SELECT e.*
FROM Employee e,
     (SELECT id,
             Date_Hired,
             row_number() OVER(PARTITION BY Department ORDER BY id DESC) AS rn
      FROM Employee e
      WHERE YEAR (e.Date_Hired) = 2021) sub
WHERE rn <= 2
  and e.id = sub.id
ORDER by e.Date_Hired DESC
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading