DATEDIFF() to just return age with 2 decimal point

2019-08-28 06:22发布

问题:

I have a SELECT statement requesting the age of he individual when a test was made:

SELECT
   DATEDIFF(dd,BIRTH_DATE,TEST_DATE)/365.25 [Age at Result]
FROM TABLE
WHERE ID = '100'

The result comes out like 2.056125.

I saw on another post to convert to seconds and divide by 86400.0, but I was still getting 6 decimal points.

What I was looking back was to get the age as 2.05 or even round to 2.00.

Thanks

回答1:

You can cast to a decimal with the precision you want:

SELECT CAST(DATEDIFF(day, BIRTH_DATE, TEST_DATE)/365.25 as DECIMAL(10, 2)) as [Age at Result]
FROM TABLE
WHERE ID = 100;

Note: I removed the single quotes around "100". Only use single quotes if it the id is a string.



回答2:

I would use the following -

DECLARE @TestDate DATETIME = GETDATE()
DECLARE @BirthDate DATETIME = '1995-06-06 08:00:00.000'

SELECT CAST(DATEDIFF(dd,@BirthDate,@TestDate)/365.25 AS DECIMAL(10, 2)) [Age at Result]