Match sensor readings to calibration history with DuckDB ASOF JOIN
A reproducible temporal join that picks the calibration effective at measurement time and distinguishes missing and stale matches.
Archive retrospective · Topic year 2023
In this article
Use calibration effective at the measurement time
Imagine temperature sensors on a production line and a separate table of calibration changes. A report needs the calibration that was in effect when each reading was taken. Applying the latest calibration to every historical reading would change data from before the equipment was adjusted. Joining on equal timestamps would miss most readings. A DuckDB article dated September 15, 2023 explains ASOF JOIN as a way to perform this kind of temporal lookup. This example uses a small maintenance history. A reading has a timestamp and device ID, while its calibration has an effective timestamp and a correction. Our business rule assigns a calibration that starts at the exact measurement time to the new regime. The calculation adds a small integer. In a real plant, unit conversion and a full calibration model need their own verification.
Separate matching from acceptable age
First match on the device ID. Then require measurement time to be at or after calibration start. There can be several historical candidates for a device, and the as-of join picks the nearest eligible one. A left join keeps the readings for which no calibration exists. That is important if reading counts are part of the report. This business scenario additionally refuses to apply calibrations more than three minutes old. A value exactly three minutes old still passes. The two decisions matter for device B, which has a calibration one minute after its reading, and device A at 10:09, which has a matching calibration four minutes in the past. Device B has no eligible historical match. Device A has a match whose age is unacceptable. A support team can assign different follow-up work to each outcome.
Run the five-reading SQL fixture
After sorting the output, the first row is device A at 09:59. Its earliest calibration starts at 10:00, so the result is missing. At 10:01 the correction adds two to produce 12. The 10:05 reading occurs at the exact start of a new calibration and becomes 16. The reading at 10:09 has a past match but is stale under the three-minute rule, so it has no corrected value. Device B at 10:03 cannot use a calibration starting at 10:04. The fixture yields five rows, two usable corrections, two missing matches, and one stale match. It requires no actual sensor data. Both timestamp columns use a common clock in this demonstration. Selecting the right-hand effective timestamp explicitly keeps the source of a correction visible during troubleshooting. The test output provides a comparison point after a schema or boundary rule changes.
WITH readings(sensor, measured_at, raw_value) AS (
VALUES ('A', TIMESTAMP '2023-09-15 09:59:00', 9),
('A', TIMESTAMP '2023-09-15 10:01:00', 10),
('A', TIMESTAMP '2023-09-15 10:05:00', 11),
('A', TIMESTAMP '2023-09-15 10:09:00', 12),
('B', TIMESTAMP '2023-09-15 10:03:00', 20)
), calibrations(sensor, effective_at, correction) AS (
VALUES ('A', TIMESTAMP '2023-09-15 10:00:00', 2),
('A', TIMESTAMP '2023-09-15 10:05:00', 5),
('B', TIMESTAMP '2023-09-15 10:04:00', 8)
), matched AS (
SELECT r.*, c.effective_at, c.correction,
CASE
WHEN c.effective_at IS NULL THEN 'missing'
WHEN r.measured_at - c.effective_at > INTERVAL '3 minutes' THEN 'stale'
ELSE 'usable'
END AS quality
FROM readings r ASOF LEFT JOIN calibrations c
ON r.sensor = c.sensor AND r.measured_at >= c.effective_at
)
SELECT sensor, measured_at, effective_at, quality,
CASE WHEN quality = 'usable' THEN raw_value + correction END AS adjusted_value
FROM matched
ORDER BY sensor, measured_at;
Resolve conflicts at identical effective times
The calibration source can deliver two records with equal device and effective time. Resolve equivalent replays or apply an approved source revision before the temporal join. If two values disagree and the source has no defined ordering, route the conflict to review. The resulting calibration history should supply one row per device and start time. Convert local timestamps to a shared time basis if the equipment provides offsets or zone data. During a daylight saving transition, the same displayed clock time might identify two different instants. Keep the original device time separately if it helps diagnose sensor drift. Also check whether device IDs can be reused across facilities or hardware replacements. Such reuse can turn an otherwise correct temporal join into a cross-device match. Future-dated calibration rows can remain available for measurements taken after their effective boundary.
Handle late calibration and repeatable reports
A late calibration can make yesterday's report differ from a report recalculated today. Store both effective time and the time the information reached the system if the distinction matters. Matching on effective time gives the best history available today. An audit report might need to reconstruct what was known at a particular close. In that case record the ingestion cutoff and apply it to calibration history before the temporal join. Report how many readings were usable, stale, and missing alongside the last update on each input. An abrupt change in coverage may reflect delayed calibration records or a genuine maintenance gap. The fixture demonstrates result shape and boundaries. Use a representative distribution of devices and historical depth to assess runtime. A simple acceptance rule checks that the output retains every selected left-side reading. When users need to explain a revised result, show the reporting version and input cutoff beside it.
Reader discussion
Which bottleneck would you expect as this solution scales?
No comments yet. Be the first to contribute.
Write a comment