All problems

Who's Been Here the Longest?

mediumSQLDatesSorting

Kestrel Labs is holding a small ceremony for the people who were there at the start of each team — the first hire on Engineering, the first on Sales, and so on. The office manager needs their names and the dates, one line per team.

Reading the earliest date in the whole company is easy and answers the wrong question: it would name one person and leave three teams unrepresented. Each team has its own earliest date, none of those dates is recorded anywhere, and the person attached to a date only comes back if the query hands you the whole row rather than the date on its own.

employees — one row per person. hire_date is the day they started, written as YYYY-MM-DD so that ordinary text comparison puts dates in true chronological sequence. department_id says which team they sit on.

id name department_id salary hire_date manager_id
1 Ava Chen 1 145000 2021-03-14 NULL
2 Ben Ortiz 1 118000 2022-06-01 1
3 Cara Novak 1 121000 2023-01-10 1
4 Deshawn Lee 2 95000 2020-09-23 NULL
5 Elin Kask 2 88000 2022-11-05 4
6 Farid Amiri 3 76000 2023-04-18 NULL
7 Grace Kim 4 132000 2021-07-30 NULL
8 Hugo Silva 4 110000 2023-02-14 7
9 Ines Duarte 4 104000 2023-08-01 7
10 Jonas Weber 2 91000 2021-12-19 4

The table already exists in the database — there is nothing to create or load.

Task: Write a query returning three columns, department_id, name and hire_date, with one row for the earliest-hired person on each team. If two people on the same team started on the same day, both appear. Rows come back in ascending department_id order.

Example output — shape only, on an invented company; the two rows for team 6 show what happens when the two longest-serving people started on the same day.

department_id name hire_date
5 Anton Reis 2019-02-11
6 Lena Fournier 2020-05-30
6 Mira Kovac 2020-05-30

Sign in to solve this problem

Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.

Sign in

Discussion

Sign in to join the discussion — reading is open to everyone.

Loading comments…