XI - SQL
I would like to be able to determine people's ages from their birthdates in a Crystal formula.
I have a rather long SQL statement that will do it outside of Crystal, but I'm not sure how to alter it to work within Crystal, if that's even the direction I should be going in.
The birthdate in the field (table.DOB) I'm working with is in 'YYYYMMDD' format.
Here is the SQL code I have:
My end goal is to determine the age, then group the report by age groups. I've got the age group formula where I think it will work, it's just determining the age itself is where my problem lies. Any help is appreciated.
"I have no idea what's going on." -Towelie
I would like to be able to determine people's ages from their birthdates in a Crystal formula.
I have a rather long SQL statement that will do it outside of Crystal, but I'm not sure how to alter it to work within Crystal, if that's even the direction I should be going in.
The birthdate in the field (table.DOB) I'm working with is in 'YYYYMMDD' format.
Here is the SQL code I have:
Code:
DECLARE @dob_input CHAR(8)
,@dob_datetime DATETIME
,@dob_day_of_year INTEGER
,@now_day_of_year INTEGER
,@age_in_years INTEGER
-- input format yyyymmdd
SET @dob_input = '19710916'
-- convert input date format to SQL DATETIME format
SET @dob_datetime = CAST( SUBSTRING( @dob_input, 1, 4 ) + '-' + SUBSTRING( @dob_input, 5, 2 ) + '-' + SUBSTRING( @dob_input, 7, 2 ) AS DATETIME )
-- determine the birthdate 'day of year'
SET @dob_day_of_year = DATEPART( dy, @dob_datetime )
-- determine the current 'day of year'
SET @now_day_of_year = DATEPART( dy, CURRENT_TIMESTAMP )
-- Remove comment line below if you want to see the intermediate values.
--SELECT @dob_datetime, @dob_day_of_year, @now_day_of_year
-- calculate the number of years between date of birth and now (the person's age)
SET @age_in_years = CASE WHEN @dob_day_of_year > @now_day_of_year
THEN DATEDIFF( yy, @dob_datetime, CURRENT_TIMESTAMP ) - 1
ELSE DATEDIFF( yy, @dob_datetime, CURRENT_TIMESTAMP )
END -- CASE
SELECT @age_in_years
My end goal is to determine the age, then group the report by age groups. I've got the age group formula where I think it will work, it's just determining the age itself is where my problem lies. Any help is appreciated.
"I have no idea what's going on." -Towelie