开发者

SQL Query to find average of difference between dates

开发者 https://www.devze.com 2023-04-06 21:27 出处:网络
I have a column that has data like Date 13/8/2011 2/9/2011 10/9/2011 20/9/2011 I need to write a SQL query/procedure that will help me get the average of the differences between the dates.

I have a column that has data like

Date
13/8/2011
2/9/2011
10/9/2011
20/9/2011

I need to write a SQL query/procedure that will help me get the average of the differences between the dates. For the above exa开发者_JS百科mple it would be (19+8+10)/3=12.33 Please help with this.

Thanks in Advance, Geetha


Try this:

SELECT DATEDIFF(
    day, 
    MIN(date_col), 
    MAX(date_col)) / (COUNT(date_col)-1) AS mean_val
FROM your_table

Thanks to ypercube for his suggestion:

SELECT
  CASE
    WHEN COUNT(date_col) < 2 THEN 0
    ELSE DATEDIFF(
        day, 
        MIN(date_col), 
        MAX(date_col)) / (COUNT(date_col)-1)
  END
  as mean_val
FROM your_table


I don't know your RDBMS, but this is from SQL Server. Also, one of your calcs is wrong - 02/09/2011 - 13/08/2011 is 20, not 19.

create table dates (
    myDate  date
)

insert into dates
values ({d '2011-08-13'}), 
    ({d '2011-09-02'}), 
    ({d '2011-09-10'}), 
    ({d '2011-09-20'})

;with orderedDates as (
    select ROW_NUMBER() OVER (order by myDate) as row, myDate
    from dates
), datediffs as (
    select DATEDIFF(dd, o2.myDate, o1.myDate) as diff
    from orderedDates o1 left outer join
        orderedDates o2 on o1.row = o2.row + 1
)
select AVG(cast(diff as decimal))
from datediffs
where diff is NOT NULL

Result produced is 12.667: (20 + 8 + 10)/3.

0

精彩评论

暂无评论...
验证码 换一张
取 消