Averaging dates in oracle sql

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 06:17:27

问题


Is there a way to average multiple dates in oracle? avg doesn't do any good.

Thanks.


回答1:


The definition of an "average date" is subjective, but you could convert your dates to a Julian number, then average those, round it off, then convert back to a date.

create table dates (dt DATE);

insert into dates 
values ('24-APR-2012');
insert into dates 
values ('01-JAN-2012');
insert into dates 
values ('01-JAN-2013');
insert into dates
values ('25-DEC-1900');


select to_date(round(avg(to_number(to_char(dt, 'J')))),'J')
from dates;

Here's the SQL Fiddle: http://sqlfiddle.com/#!4/98ce9/1




回答2:


The 'median' function in oracle in a neat way does exactly what other answers do.

Here is a link to the Oracle documentation - https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions086.htm

It can take as an arg a numeric datatype or a non-numeric datatype that can be converted implicitly to a number.

SQL> desc x1
Name                                      Null?    Type
----------------------------------------- -------- ----------------------------
A                                         NOT NULL NUMBER
D                                                  DATE

SQL> select * from x1;

     A D
---------- ---------
     1 11-DEC-14
     2 13-DEC-14
     3 22-DEC-14
     4 02-DEC-14
SQL> select median(d) from x1;

MEDIAN(D)
---------
12-DEC-14



回答3:


Oracle handles some date arithmetic naturally - eg TRUNC(SYSDATE) + 1 will return tomorrow's date.

So another approach is to compare your date to a constant:

1) compare distance in days to a constant (eg SYSDATE)

2) average, and then round, that calculation

3) compare the average back to SYSDATE & convert back to date.

Here's some code that does this (replace dt with whatever field has your data)

 TO_DATE(
    TRUNC(SYSDATE) - ROUND(AVG(TRUNC(SYSDATE) - TRUNC(dt)))
 )

On some sample data this ran in just under half the time of Dan A.'s approach above, and produced the same output. Only tested it against data with dates in the past, but I don't see any obvious reason that it wouldn't generalize (famous last words when dealing with DATETIME data, I realize...)




回答4:


SYSDATE + AVG( dt - SYSDATE )

No need to convert a date to a date. Truncate entire expression if you don't want the time included in result. Truncate the date column (dt) if you don't want times to be used in the computation of the average. MEDIAN is not the same as AVG.



来源:https://stackoverflow.com/questions/10307353/averaging-dates-in-oracle-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!