Reputation: 1
Query is below
select fname,lname,DATEDIFF(YY,birthdate,GETDATE()) as age from EMPLOYEE where age = 72
but there is an error says --> "Invalid column name 'age'.
How can i solve it? Thank you!
Upvotes: 0
Views: 30
Reputation: 1269443
My favorite way to do this in SQL Server uses a lateral join:
select e.fname, e.lname, v.age
from EMPLOYEE e cross apply
(values (DATEDIFF(year, birthdate, GETDATE())) v(age)
where v.age = 72;
Notes:
Upvotes: 1
Reputation: 38023
In SQL Server you have to repeat the expression (from the select
) to use it in the where
clause:
select fname,lname,DATEDIFF(Year,birthdate,GETDATE()) as age
from EMPLOYEE
where DATEDIFF(Year,birthdate,GETDATE()) = 72
Unless using something like cross apply()
to create the calculated field.
Upvotes: 1
Reputation: 39457
Just repeat the expression in the where
clause:
select fname,
lname,
DATEDIFF(YY, birthdate, GETDATE()) as age
from EMPLOYEE
where DATEDIFF(YY, birthdate, GETDATE()) = 72
Upvotes: 0