Home >Database >Mysql Tutorial >How to Accurately Calculate Age in Years from a Date of Birth in SQL Server?
Accurately calculate age by date of birth in SQL Server
Question:
How to convert a date of birth stored as nvarchar(25) to a date in SQL Server and subsequently calculate its corresponding age in years?
Sample data:
ID | Name | DOB |
---|---|---|
1 | John | 1992-01-09 00:00:00 |
2 | Sally | 1959-05-20 00:00:00 |
Expected output:
ID | Name | AGE | DOB |
---|---|---|---|
1 | John | 31 | 1992-01-09 00:00:00 |
2 | Sally | 64 | 1959-05-20 00:00:00 |
Answer: Calculate age accurately
The originally proposed method faced challenges in accounting for leap years and irregularities in the number of days in the month. Modern SQL Server versions provide us with improved techniques to resolve these complexities.
The best way to calculate age in whole numbers:
This method is simple and direct, but the accuracy may be slightly lower than the decimal method.
<code class="language-sql">SELECT (YEAR(GETDATE()) - YEAR(DOB)) - CASE WHEN MONTH(GETDATE()) < MONTH(DOB) OR (MONTH(GETDATE()) = MONTH(DOB) AND DAY(GETDATE()) < DAY(DOB)) THEN 1 ELSE 0 END AS AgeIntYears FROM YourTable;</code>
The best way to calculate age as a decimal:
This method uses the DATEDIFF
function and the CASE
statement to accurately calculate age and considers whether the birthday has passed in the current year.
<code class="language-sql">SELECT DATEDIFF(year, DOB, GETDATE()) - CASE WHEN MONTH(GETDATE()) < MONTH(DOB) OR (MONTH(GETDATE()) = MONTH(DOB) AND DAY(GETDATE()) < DAY(DOB)) THEN 1 ELSE 0 END AS AgeYearsDecimal FROM YourTable;</code>
Please note that the above code assumes that the DOB
column has been converted to the DATE
type. If DOB
is still of type nvarchar(25)
, you need to add type conversion in the query, for example: CONVERT(DATE, DOB, 120)
. Choosing the appropriate transformation style depends on the specific format of your DOB
data. For example, CONVERT(DATE, DOB, 120)
is for 'yyyy-mm-dd hh:mi:ss' format. You may need to adjust this section to suit your data format. The final query should look something like:
<code class="language-sql">SELECT DATEDIFF(year, CONVERT(DATE, DOB, 120), GETDATE()) - CASE WHEN MONTH(GETDATE()) < MONTH(CONVERT(DATE, DOB, 120)) OR (MONTH(GETDATE()) = MONTH(CONVERT(DATE, DOB, 120)) AND DAY(GETDATE()) < DAY(CONVERT(DATE, DOB, 120))) THEN 1 ELSE 0 END AS AgeYearsDecimal FROM YourTable;</code>
Replace YourTable
with your table name. Choosing the integer or decimal method depends on your precision needs. The decimal method is more precise, but the integer method is more concise.
The above is the detailed content of How to Accurately Calculate Age in Years from a Date of Birth in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!