Oracle SQL日期问题:查询最近入职员工姓名
Oracle SQL Solution to Find Most Recently Joined Employees
Hey there! Let's figure out how to pull the list of employees who joined the company most recently using Oracle SQL. Here's a breakdown tailored to your data and requirements:
What We Need to Do
Retrieve the names of employees with the latest joining date from the provided employee dataset.
Sample Input Data
| emp | Date of joining |
|---|---|
| neil | 31-dec-2010 |
| tom | 31-dec-2008 |
| fred | 31-dec-2011 |
| scott | 31-dec-2011 |
| james | 31-dec-2010 |
| shane | 31-dec-2011 |
| brendon | 31-dec-2010 |
| kane | 31-dec-2009 |
| chris | 31-dec-2010 |
| matthew | 31-dec-2011 |
Expected Output
| emp | Date of Joining |
|---|---|
| fred | 31-dec-2011 |
| scott | 31-dec-2011 |
| shane | 31-dec-2011 |
| matthew | 31-dec-2011 |
Solution 1: Simple Subquery Approach
This is the most straightforward method—first find the latest joining date, then filter employees who match that date:
SELECT emp, "Date of joining" AS "Date of Joining" FROM your_employee_table WHERE "Date of joining" = (SELECT MAX("Date of joining") FROM your_employee_table) ORDER BY emp;
How it works:
- The subquery
(SELECT MAX("Date of joining") FROM your_employee_table)grabs the most recent joining date in the table. - The main query returns all employees whose joining date matches this maximum value.
- The
ORDER BY empclause sorts results alphabetically, matching your desired output order.
Solution 2: Window Function (RANK()) Approach
If you need more flexibility (like fetching the top 2 most recent hiring batches later), use a window function:
WITH ranked_hires AS ( SELECT emp, "Date of joining" AS "Date of Joining", RANK() OVER (ORDER BY "Date of joining" DESC) AS hire_rank FROM your_employee_table ) SELECT emp, "Date of Joining" FROM ranked_hires WHERE hire_rank = 1 ORDER BY emp;
How it works:
- The CTE (
ranked_hires) assigns a rank to each employee based on their joining date—those with the latest date get a rank of 1. - We select only rows where
hire_rank = 1to get all the most recent hires. - This method scales easily: if you ever need employees from the next most recent joining date, just adjust the
WHEREclause tohire_rank <= 2.
Important Notes:
- Replace
your_employee_tablewith the actual name of your employee table in Oracle. - Since the column name has spaces, we use double quotes (
"Date of joining") to reference it correctly (Oracle is case-sensitive with quoted identifiers).
内容的提问来源于stack exchange,提问作者bradon Mc
相关产品推荐
相关产品推荐

