如何在SOQL查询中获取平均日期

时间:2012-12-26 16:08:56

标签: sql-server tsql

我想在sql中获取平均日期,但我不知道该怎么做。我有以下字段:

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

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

2 个答案:

答案 0 :(得分:6)

您可以使用类似的内容,将日期转换为float,然后取平均值:

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 with Demo

由于您的日期值分布在多个列中,因此我执行了unpivotunion 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 with Demo

答案 1 :(得分: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