sql-serverssms-16

How to fetch values from starting of the year in MS SQL


I can get exact 3 years of value with the below code (from 01/24/2018 - 01/25/2021)

select * from datamining.dbo.EmployeeDetails
where DateOfjoining >= DATEADD(year,-3,GETDATE())

But I'm expecting the results should be from 01/01/2018 - 01/25/2021(Till date)

How do I achieve this?


Solution

  • Lots of ways. One is to combine YEAR, which extracts the numeric year value from a date and DATEFROMPARTS, which constructs a date from Year, Month, and Day componenets. EG:

    select * from datamining.dbo.EmployeeDetails
    where DateOfjoining >= DATEFROMPARTS(YEAR(DATEADD(year,-3,GETDATE())),1,1)