2

我正在尝试获取 sql 中的平均日期,但不确定如何执行此操作。我有以下字段:

ID   Date1             Date2                   Date3
1    05/04/2012        08/09/2012             07/02/2012

我想添加另一列显示 ID 号 1 的平均日期。我只完成了平均数字,但从未完成平均日期。谢谢

4

2 回答 2

6

你可以使用这样的东西,它将日期转换为 afloat然后取平均值:

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;

请参阅带有演示的 SQL Fiddle

由于您的日期值跨越多个列,因此我先执行unpivotorunion all以获取单个列中的值,然后取该值的平均值。

这是使用该UNPIVOT函数的另一个示例:

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;

请参阅带有演示的 SQL Fiddle

于 2012-12-26T16:14:42.820 回答
1
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
于 2012-12-26T16:27:02.500 回答