Create a Table in SQL Server
This is my employee table with few rows in it.
Or, you can use this sample Employee table. Create the table.
Find Employees Hired in the Last n Months
Here’s the query.
DECLARE @n INT SET @n = 3 SELECT * FROM Employees WHERE DOJ >= DATEADD(M, -@n, GETDATE())
I am using a variable to define the number of months, since its n months. So, the value can be anything like 3, 4, 6 etc.
This is more dynamic and you can execute this query using a Stored Procedure, if it’s a repeated process.
Here’s the output. (Assuming it’s the month of May)
Find the Employees who have been Hired in the Last 4 Months
Well, you can even use this query, if you know the number of months.
SELECT *FROM Employees WHERE DOJ >= DATEADD(MONTH, -4, GETDATE())
Now, let’s understand the SQL function, which is responsible for this output.
DATEADD() function
The DATEADD() function returns a date time (smalldatetime). Its syntax is,
DATEDADD(interval, increment (int), expression (date))
Note: The DATEADD() function is also supported by Azure SQL Database.