我有一个包含
等数据的列Date
13/8/2011
2/9/2011
10/9/2011
20/9/2011
我需要编写一个SQL查询/过程来帮助我获得日期之间差异的平均值。 对于上面的例子,它将是(19 + 8 + 10)/3=12.33 请帮助解决这个问题。
先谢谢, 格塔
答案 0 :(得分:7)
试试这个:
SELECT DATEDIFF(
day,
MIN(date_col),
MAX(date_col)) / (COUNT(date_col)-1) AS mean_val
FROM your_table
感谢ypercube的建议:
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
答案 1 :(得分:4)
我不知道您的RDBMS,但这是来自SQL Server。此外,您的一个计算错误 - 02/09/2011 - 13/08/2011是20,而不是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
产生的结果是12.667:(20 + 8 + 10)/ 3.