I am trying to get the Average Date in sql and am not sure how to do this. I have the following fields:
ID Date1 Date2 Date3
select id, date1, date2, date3
,Cast(
(cast(date1 as Float) + cast(date2 as Float) + cast(date3 as Float))/3
as Datetime) as AvgDate
from yourtable
You could use something like this, which casts the date to a float
and then takes the average:
select t.id, t.date1, t.date2, t.date3, src.AvgDate
from yourtable t
inner join
(
select id, cast(avg(date) as datetime) AvgDate
from
(
select id, cast(cast(date1 as datetime) as float) date
from yourtable
union all
select id, cast(cast(date2 as datetime) as float) date
from yourtable
union all
select id, cast(cast(date3 as datetime) as float) date
from yourtable
) x
group by id
) src
on t.id = src.id;
See SQL Fiddle with Demo
Since your date values are across multiple columns, I performed an unpivot
or union all
to get the values in a single column first then take the average of that value.
Here is another example of using the UNPIVOT
function:
select t.id, t.date1, t.date2, t.date3, src.AvgDate
from yourtable t
inner join
(
select id, cast(avg(date) as datetime) AvgDate
from
(
select id, cast(cast(date as datetime) as float) date
from yourtable
unpivot
(
date
for col in (date1, date2, date3)
) unpiv
) x
group by id
) src
on t.id = src.id;
See SQL Fiddle with Demo