-1

I have a list of people who visited a certain location during the year of 2017. The goal is to narrow the list down to only people who were within a certain age range when they visited. The query is pretty simple:

SELECT DISTINCT
    VisitID
    ,VisitDate
    ,PersonID
    ,Age
    ,DateOfBirth

FROM Visit v JOIN Demographics d ON v.PersonID = d.PersonID

WHERE VisitDate BETWEEN '01/01/2017' AND '12/31/2017'
AND Age BETWEEN 45 AND 75

The issue is that the way this query is written, it's pulling in patients who are currently within that age range and might not necessarily have been during 2017.

What I'd like to be able to do is add a line of code that calculates how old the person was when they visited by comparing the VisitDate and DateOfBirth fields. I've written code before to calculate someone's age based on DOB when I didn't have an age field available, but this is a different situation. And so far none of the tutorials or sample code I've found have been in the right context. How might I go about doing this?

EJF
  • 451
  • 3
  • 9
  • 28

1 Answers1

0

-- this should give you what you need in years:

SELECT DATEDIFF(YEAR, DateofBirth, DateOfVisit) AS AgeWhenVisit
Brad
  • 3,454
  • 3
  • 27
  • 50
  • 2
    No it won't. This will return the number of Jan 1sts that have passed between the DateOfBirth and DateOfVisit. – Tab Alleman May 07 '18 at 19:42