Home > front end >  SQL WHERE clause - best way to display data from every 3 years
SQL WHERE clause - best way to display data from every 3 years

Time:01-01

I'm trying to find the best way to display a list of employees by hire year in intervals of every 3 years (calculated from the year that the report/query was executed). For example, if 2021 is the report execution year, then it would only show employees hired in the years of 2012, 2015, 2018, etc

The WHERE clause below works, but it's clunky and I'm sure there's a better way to increment the years without using a long list of OR statements that add -6, -9, etc

WHERE
  (EmployeesTable.[Hire Year] = @ExecutionYear -3)
  OR 
  (EmployeesTable.[Hire Year] = @ExecutionYear -6)
  OR
  (EmployeesTable.[Hire Year] = @ExecutionYear -9)

CodePudding user response:

try this...

WHERE @ExecutionYear - EmployeesTable.[Hire Year] IN (3,6,9)

CodePudding user response:

How about using a modulo?

where (EmployeesTable.[Hire Year] - @ExecutionYear) % 3 = 0
  • Related