首页 > 解决方案 > Oracle SQL - 从午夜的日期时间字段中查找平均时间

问题描述

第一次发布问题,如果不清楚,请道歉。

我想根据与业务日期相比的生成日期时间字段来查找文件的平均交付时间。我遇到的问题是文件可能会在午夜之前或之后交付,这超出了我的平均值。

这是我正在测试的数据集;

select ID, business_date, generation_date
from table
where business_date >= to_date('20190705','yyyyMMdd hh24mi') and
      subscription_id = 'Report 1'

ID  BUSINESS_DATE   GENERATION_DATE
Report 1    09/07/2019  09/07/2019 23:02
Report 1    08/07/2019  09/07/2019 01:10
Report 1    05/07/2019  05/07/2019 20:58
Report 1    10/07/2019  10/07/2019 21:54

第二行的 generation_date 是在午夜之后,所以当我尝试下面的代码时,它给出的平均值不正确。

select id, 
to_char(trunc(sysdate) + 
               avg(cast(generation_date as date) - cast(trunc(generation_date) as date))
               , 'hh24mi') as ""Average_Delivery_Time""
from table
where a.business_date >= to_date('20190705','yyyyMMdd hh24mi')
and id = 'Report 1'
group by id

ID  Average_Delivery_Time
Report 1    16:46:27

我曾考虑过拆分日期和时间,然后根据 business_date 执行一些计算,但我确信必须有更好的方法来找到平均时间(考虑到不同的日期)。

正确平均时间:22:46:26

任何有关如何在 SQL 中执行此操作的帮助将不胜感激。

看上面

看上面

标签: sqloracle

解决方案


Does this do what you want?

avg(generation_date - trunc(business_date))

I am not sure why you are converting what look like dates into dates.


推荐阅读