Hi all,
I am trying to take a date field which is of varchar data type transform it into date data type and then use it to calculate the average of that date.
I have tried a few different ways but the syntax must be incorrect.
Any suggestions welcome please.
SELECT
DATEADD(DAY, 0, AVG(DATEDIFF(DAY, 0, CAST(date_varchar AS date)))) AS avg_date
FROM ( VALUES('20190101'),('20190201') ) AS dates(date_varchar)
--FROM ( VALUES('20190101'),('20190201'),('20190301') ) AS dates(date_varchar)
the date on the left is formatted using this line CONVERT(date,LEFT(dom.Value,8),112) and the one on the right is the value stored. how can i use the value on the left to calculate the average age?
or do you have other suggestions?
thanks in advance.
the date on the left is formatted using this line CONVERT(date,LEFT(dom.Value,8),112) and the one on the right is the value stored. how can i use the value on the left to calculate the average age?
or do you have other suggestions?
thanks in advance.
create table #confiz(dob date);
insert into #confiz
select '2012-08-01' union
select '1970-01-01' union
select '1988-01-01' union
select '2012-08-01' union
select '1967-01-01' union
select '1982-01-01' union
select '2001-01-01' union
select '2012-01-01' union
select '1999-01-01' union
select '1997-01-01' union
select '1995-01-01' union
select '2010-01-01' union
select '1996-01-01'
;with ages
as
(
select datediff(year, dob, getdate()) _ages, *
From #confiz
)
select AVG(_ages) from ages
--24 is the average age
drop table #confiz
SELECT CAST(AVG(age) AS decimal(5, 2)) AS avg_age
FROM #confiz
CROSS APPLY (
SELECT CAST(DATEDIFF(YEAR, dob, GETDATE()) -
CASE WHEN CONVERT(varchar(5), dob, 101) >
CONVERT(varchar(5), GETDATE(), 101)
THEN 1 ELSE 0 END AS decimal(5, 2)) AS age
) AS age_calc