如何在Toad for Oracle中将计算的时差转换为小数?

9q78igpj  于 2023-06-29  发布在  Oracle
关注(0)|答案(2)|浏览(126)

我正在查询名为SENSORMAINTAB的模式中名为SENSOR_INSPECTIONS的表。该表格由处理由10,000个传感器组成的批次/批次的机器提供。当传感器通过机器时,机器对每个传感器进行多次“检查”。
我在下面编写了一个查询,以确定批次/批次的最新和最早检查时间之间的差异(在名为“持续时间”的自定义列中)(这为我提供了机器运行的持续时间)。
查询是:

SELECT LOT_ID, 
    MAX(INSPECTION_TIME), 
    MIN(INSPECTION_TIME), 
    MAX(INSPECTION_TIME) - MIN(INSPECTION_TIME) AS Duration
FROM SENSORMAINTAB.SENSOR_INSPECTIONS
WHERE LOT_ID = 1392353501 AND INSPECTION_ID = 49
GROUP BY LOT_ID

我得到的结果如下:
| 最大值(检查时间)|最小值(检查时间)|持续时间| DURATION |
| - -----|- -----|- -----| ------------ |
| 2019 - 05 - 22 00:06:03.529000| 2019 - 05 - 27 17:36:50.657000| 2019 - 02 - 29 00:00:00| +00 02:29:12.872000 |
我是否可以在这个结果输出中添加一个额外的列,以显示以小时为单位的时间差,并以小数表示?
29分钟,12秒和0.872秒是0.48690888889小时根据谷歌。我四舍五入到0.487(3个小数位)。
对于上面的例子,它将是:
| 最大值(检查时间)|最小值(检查时间)|持续时间|圆形| ROUNDED |
| - -----|- -----|- -----|- -----| ------------ |
| 2019 - 05 - 22 00:06:03.529000| 2019 - 05 - 27 17:36:50.657000| 2019 - 02 - 29 00:00:00| 2.487| 2.487 |

kxeu7u2r

kxeu7u2r1#

两个时间戳相减得到interval day to second。如果要保留亚秒级精度,则需要提取间隔的每个部分并进行数学运算。

select t.*,
    round(
          extract(day    from duration)  * 24
        + extract(hour   from duration) 
        + extract(minute from duration) / 60
        + extract(second from duration) / 60 / 60,
        3
    ) as rounded
from (
    select lot_id, 
        max(inspection_time) as max_time, 
        min(inspection_time) as min_time,  
        max(inspection_time) - min(inspection_time) as duration
    from sensormaintab.sensor_inspections 
    where lot_id = 1392353501 and inspection_id = 49 
    group by lot_id
) t

使用子查询可以避免重复max(...) - min(...)表达式(我们也可以在横向连接中这样做)。

a64a0gku

a64a0gku2#

如果你不受小数秒的困扰,那么把时间戳转换成日期,然后减去一天的一小部分,然后乘以24:

SELECT LOT_ID, 
    MAX(INSPECTION_TIME), 
    MIN(INSPECTION_TIME), 
    (CAST(MAX(INSPECTION_TIME) AS DATE) - CAST(MIN(INSPECTION_TIME) AS DATE)) * 24
      AS Duration
FROM SENSORMAINTAB.SENSOR_INSPECTIONS
WHERE LOT_ID = 1392353501 AND INSPECTION_ID = 49
GROUP BY LOT_ID

如果需要小数秒,则将时间戳截短到分钟的开始,并找到差值,然后包括秒差:

SELECT LOT_ID, 
    MAX(INSPECTION_TIME), 
    MIN(INSPECTION_TIME), 
    (
      TRUNC(MAX(INSPECTION_TIME), 'MI')
      - TRUNC(MIN(INSPECTION_TIME), 'MI')
    ) * 24
    + (
      EXTRACT(SECOND FROM MAX(INSPECTION_TIME))
      - EXTRACT(SECOND FROM MIN(INSPECTION_TIME))
    ) / 60 / 60
      AS Duration
FROM SENSORMAINTAB.SENSOR_INSPECTIONS
WHERE LOT_ID = 1392353501 AND INSPECTION_ID = 49
GROUP BY LOT_ID

相关问题