Sunday, April 20, 2014

Select people older than 65

You can adjust Jose's code to match your number:



declare @Date65 date;
set @Date65= DateAdd(year, -65, CURRENT_TIMESTAMP);

declare @beginningYear65Plus1 date
set @beginningYear65Plus1=DATEADD(yy, DATEDIFF(yy,0,@Date65)+1,0)

select *, year(getdate())-YEAR(birthdate) as age
from AdventureWorksDW.[dbo].[DimCustomer]
where birthdate <= @beginningYear65Plus1;



But if you want to get more accurate data, you can use the following query:



Select * from (select *, DATEDIFF(yy, [birthdate], current_timestamp) - CASE WHEN
(MONTH([birthdate]) > MONTH(current_timestamp)) OR (MONTH([birthdate]) = MONTH(current_timestamp)
AND DAY([birthdate]) > DAY(current_timestamp)) THEN 1 ELSE 0 END as age

from AdventureWorksDW.[dbo].[DimCustomer]
) t

where age >= 65





No comments:

Post a Comment