How to get Avg Date in SQL Qry

后端 未结 2 1155
说谎
说谎 2021-01-15 14:45

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         


        
2条回答
  •  别那么骄傲
    2021-01-15 15:21

    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

提交回复
热议问题