简体   繁体   中英

SQL Calculate the age .use DatePart on DATE()) minus year of birth

Find the star number, name, date of birth, and current age of all stars who were born before January 1, 1925 and who are still living. Calculate the age based on the current year (use DatePart on DATE()) minus year of birth.

Current Query :

SELECT StarNum, FirstName,LastName,StarBorn,StarDied,Datepart("yyyy",StarBorn- date()) AS age
FROM Star
WHERE StarBorn < #01/01/1925# AND StarDied IS NULL

Instead of Datepart use Datediff to calculate age .

and the formula i used to calculate age is

DATEDIFF("h",DOB,date())/8766

Try this.

SELECT StarNum, FirstName,LastName,StarBorn,
       StarDied,DATEDIFF("h",StarBorn,date())/8766  AS age
FROM Star
WHERE StarBorn < #01/01/1925# AND StarDied IS NULL

Use this to get a more accurate age of a person. I believe this is specific to the day of birth.

select case 
            when cast(getdate() as date) = cast(dateadd(year, (datediff(year, '1996-09-09', getdate())), '1996-09-09') as date)
                then dateDiff(yyyy,'1996-09-09',dateadd(year, 0, getdate()))
            else dateDiff(yyyy,'1996-09-09',dateadd(year, -1, getdate()))
        end as MemberAge
go

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM