I am Querying a Table called SENSOR_INSPECTIONS in a Schema called SENSORMAINTAB. The table is fed from a machine that processes Lots/Batches that are composed of 10, 000 Sensors. The Machine makes multiple 'Inspections' of each Sensor as the Sensors pass through the Machine.
I have written a Query below to determine the difference (in a custom column called 'Duration') between the Latest and Earliest Inspection Time of a Lot/Batch (which gives me the duration that the machine was running for).
The Query is:
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
The Result I get is the following:
| LOT_ID | MAX(INSPECTION_TIME) | MIN(INSPECTION_TIME) | DURATION |
|---|---|---|---|
| 1392353501 | 27/05/2023 20:06:03.529000 | 27/05/2023 17:36:50.657000 | +00 02:29:12.872000 |
Is it possible for me to add an extra Column to this result output that shows the time difference in Hrs expressed as a decimal?
29 Mins, 12 Seconds and 0.872 Seconds is 0.48690888889 Hrs according to Google. I rounded this to 0.487 (3 Decimal Places).
So for the above Example, it would be:
| LOT_ID | MAX(INSPECTION_TIME) | MIN(INSPECTION_TIME) | DURATION | ROUNDED |
|---|---|---|---|---|
| 1392353501 | 27/05/2023 20:06:03.529000 | 27/05/2023 17:36:50.657000 | +00 02:29:12.872000 | 2.487 |
The substraction of the two timestamps gives you an
interval day to second. If you want to retain the sub-second precision, you need to extract each part of the interval and do the math.Using a subquery avoids repeating the
max(...) - min(...)expression (we could also do this in a lateral join).