Averaging dates in oracle sql

后端 未结 4 1653
逝去的感伤
逝去的感伤 2020-12-10 07:06

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

Thanks.

相关标签:
4条回答
  • 2020-12-10 07:13

    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...)

    0 讨论(0)
  • 2020-12-10 07:27

    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.

    0 讨论(0)
  • 2020-12-10 07:34

    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

    0 讨论(0)
  • 2020-12-10 07:35

    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
    
    0 讨论(0)
提交回复
热议问题