Find Employees Who Have Had the Same Job Title for More Than 5 Years Query Using MS SQL Server?
To find employees who have had the same job title for more than 5 years, you need to:
- Identify the job title history for each employee.
- Determine if an employee has held the same job title for more than 5 years.
Assuming you have an EmployeeHistory
table that tracks job titles and their effective dates:
EmployeeHistory
:EmployeeID
JobTitle
StartDate
(date when the job title was assigned)EndDate
(date when the job title was changed, NULL if currently held)
Here’s a SQL query to find employees who have had the same job title for more than 5 years:
SQL Query
Explanation:
CTE
JobTitleDurations
:ISNULL(EndDate, GETDATE()) AS EndDate
: IfEndDate
is NULL (indicating the job title is currently held), use the current date (GETDATE()
) for calculation.DATEDIFF(YEAR, StartDate, ISNULL(EndDate, GETDATE())) AS DurationYears
: Calculates the number of years the job title has been held.
CTE
LongTermTitles
:MAX(DurationYears) AS MaxDurationYears
: Finds the maximum duration for eachJobTitle
per employee.HAVING MAX(DurationYears) > 5
: Filters to include only those job titles held for more than 5 years.
Final Query:
JOIN Employees e ON l.EmployeeID = e.EmployeeID
: Joins with theEmployees
table to get employee names.ORDER BY e.EmployeeID, l.JobTitle
: Orders the results byEmployeeID
andJobTitle
.
Example Data and Results
Assume you have the following data:
EmployeeHistory
Table:
EmployeeID | JobTitle | StartDate | EndDate |
---|---|---|---|
1 | Developer | 2010-01-01 | NULL |
1 | Senior Developer | 2015-01-01 | NULL |
2 | Analyst | 2012-06-01 | 2020-06-01 |
2 | Senior Analyst | 2020-06-02 | NULL |
Employees
Table:
EmployeeID | Name |
---|---|
1 | Alice |
2 | Bob |
The query would produce:
EmployeeID | Name | JobTitle | MaxDurationYears |
---|---|---|---|
1 | Alice | Developer | 13 |
1 | Alice | Senior Developer | 9 |
This result shows employees who have held the same job title for more than 5 years, along with the duration they held that title.
You can execute this query in SQL Server Management Studio or any SQL query tool connected to your SQL Server to find employees who have had the same job title for more than 5 years. Adjust the table and column names according to your actual database schema.
Post a Comment