You are absolutely right to point this out! The original query I provided does not correctly handle duplicate consecutive Device values.
It relies on LAG(Device, 1) and LAG(Device, 2) operating on the raw table. If you have:
1:00:00 On (1)
1:00:02 On (1) <-- Duplicate
1:00:05 Off (0)
And the current row is 1:00:05 Off (0):
LAG(Device, 1) would be On (1) from 1:00:02.
LAG(Device, 2) would be On (1) from 1:00:00.
If the query were looking for an OFF -> ON -> OFF pattern, this might accidentally seem to work sometimes, but for the ON -> OFF -> ON cycle definition, it will break. Specifically, when the current row is an ON event that completes a cycle, prev_device might be the same state from an intermediate duplicate, not the actual preceding different state.
Let's refine this. We first need to identify the actual points of state transition.
Revised Approach to Handle Duplicates
- Identify Actual State Transitions: Create a sequence of events where the
Device state actually changes. This means filtering out rows where the Device state is the same as the immediately preceding row (based on timestamp). The very first row in the dataset is always considered a "transition" from a conceptual "unknown" state.
- Identify Cycle Points: On this filtered list of transitions, use
LAG to find the three crucial timestamps that define a completed cycle ending in an "ON" state:
t_on_start: The timestamp when the device turned ON (start of the ON period).
t_off_start: The timestamp when the device turned OFF (start of the OFF period).
t_on_end: The timestamp when the device turned back ON (end of the OFF period, completion of the cycle).
- Calculate Durations:
- On Duration:
t_off_start - t_on_start
- Off Duration:
t_on_end - t_off_start
- Total Cycle Time:
t_on_end - t_on_start
- Compute Duty Cycle:
on_duration / total_cycle_time.
Revised SQL Query
WITH state_changes AS (
-- Step 1: Identify actual state transitions
SELECT
timestamp,
Device
FROM (
SELECT
timestamp,
Device,
LAG(Device, 1, -1) OVER (ORDER BY timestamp) AS prev_device_raw -- Use a value Device can't be (e.g., -1 if Device is 0 or 1)
FROM Status
)
WHERE Device <> prev_device_raw -- This keeps the first row and any row where state changed
),
cycle_points AS (
-- Step 2: Identify the three points of a cycle using the filtered state changes
SELECT
timestamp AS t_on_end, -- Current ON event (marks end of cycle)
Device AS current_device_state, -- Should be 1 (ON)
LAG(timestamp, 1) OVER (ORDER BY timestamp) AS t_off_start, -- Previous event (should be OFF)
LAG(Device, 1) OVER (ORDER BY timestamp) AS prev_device_state, -- Should be 0 (OFF)
LAG(timestamp, 2) OVER (ORDER BY timestamp) AS t_on_start -- Event before previous (should be ON)
FROM state_changes
)
SELECT
t_on_end AS cycle_end_time,
(JULIANDAY(t_off_start) - JULIANDAY(t_on_start)) * 86400.0 AS on_duration_seconds,
(JULIANDAY(t_on_end) - JULIANDAY(t_off_start)) * 86400.0 AS off_duration_seconds,
(JULIANDAY(t_on_end) - JULIANDAY(t_on_start)) * 86400.0 AS total_cycle_seconds,
CASE
WHEN (JULIANDAY(t_on_end) - JULIANDAY(t_on_start)) > 0 THEN -- Avoid division by zero
(JULIANDAY(t_off_start) - JULIANDAY(t_on_start))
/
(JULIANDAY(t_on_end) - JULIANDAY(t_on_start))
ELSE NULL -- Or 0, or handle as an error, depending on requirements for zero-duration cycles
END AS duty_cycle
FROM cycle_points
WHERE
current_device_state = 1 -- The cycle ends when the device turns ON
AND prev_device_state = 0 -- The preceding state must have been OFF
AND t_on_start IS NOT NULL; -- Ensures we have all three points for a full cycle
Explanation of How Unused Duplicates are Discarded
-
state_changes CTE:
-
cycle_points CTE:
- This CTE now operates on the filtered
state_changes data. So, LAG(timestamp, 1) and LAG(timestamp, 2) correctly fetch the timestamps of the actual previous state changes, not intermediate duplicate entries.
-
Final SELECT Statement:
WHERE current_device_state = 1 AND prev_device_state = 0: This condition ensures we are at a point where the device just turned ON (current_device_state = 1) from an OFF state (prev_device_state = 0). This marks the end of an OFF period and thus the end of a full ON-OFF cycle.
AND t_on_start IS NOT NULL: This ensures that there was indeed a previous ON state before the OFF state, meaning we have the three points (t_on_start, t_off_start, t_on_end) necessary to calculate a full cycle.
By first creating the state_changes CTE, we effectively "compress" the raw log into a series of true state changes, and then the logic for calculating the duty cycle can be applied to this cleaned-up data. The duplicates are discarded because they don't represent a change in the Device state compared to their immediate predecessor in the original table.