首页 > 解决方案 > 在给定的日期范围参数内检索失败之间的平均时间

问题描述

以下是我尝试过的,

select machine_id, count(incident_id) "No_Incident", 
(fail_date BETWEEN (24 * to_date('&From_date_', 'DDMMYYYY') AND to_date('&To_Date','DDMMYYYY') / count(incident_id))) "MTBF"
from mytable;

预期结果

标签: sqloracleplsql

解决方案


您可以考虑以下示例:

由于machine_id没有被聚合(例如被计算),我使用 group by 来提供每台机器的平均故障间隔时间 (MTBF)。如果您想要所有机器,只需machine_id从 SELECT 子句和 GROUP BY中删除machine_id

between当您在 select 子句中使用查询日期范围时,您的查询出现语法错误。注意。我对此进行了修改并将其放在 where 子句中。根据您执行查询的方式(eq sql 客户端),您处理参数的方式可能会有所不同。

使用甲骨文

SELECT 
    machine_id,
    count(incident_id) as "No_Incidents",
    (
      EXTRACT( 
         HOUR FROM 
         CAST(MAX(fail_date) AS TIMESTAMP) - CAST(MIN(fail_date) AS TIMESTAMP)
      ) +
      EXTRACT( 
         DAY FROM 
         CAST(MAX(fail_date) AS TIMESTAMP) - CAST(MIN(fail_date) AS TIMESTAMP)
      ) * 24
    )/count(incident_id) as "MTBF"
FROM
   mytable
WHERE
   fail_date BETWEEN to_date('&From_date_', 'DDMMYYYY') AND to_date('&To_Date','DDMMYYYY')
GROUP BY
   machine_id

在 oracle 示例中,我在找到差异之前使用CAST将日期转换为 TIMESTAMP(date_max - date_min 给出了日期间隔)。提取(使用EXTRACT)并对小时数(小时和天*24)求和得出总小时数。

使用 MySQL

SELECT 
    machine_id,
    count(incident_id) as "No_Incidents",
    (
      TIMESTAMPDIFF(HOUR,min(fail_date),max(fail_date))
    )/count(incident_id) as "MTBF"
FROM
   mytable
WHERE
   fail_date BETWEEN to_date('&From_date_', 'DDMMYYYY') AND to_date('&To_Date','DDMMYYYY')
GROUP BY
   machine_id

我还使用了TIMESTAMPDIFF MYSQL 函数来确定日期之间的时间差。


推荐阅读