Averaging dates in oracle sql

后端 未结 4 1661
逝去的感伤
逝去的感伤 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...)

提交回复
热议问题