Smart Statistics · Hands-on SQL tutorial
SQL Consecutive Dates: Turn Repeated Inspection Failures into Episodes
A list of failed checks tells you how often something was recorded. An episode view shows which issues persisted across consecutive days. Build that view without counting duplicate observations as extra days.
1 December 2026 · For UK operations and reporting teams · T-SQL
Illustrative example · all dashboard figures
Routine inspection issues: the episode view
Failed days per episode
Illustrative example · review queue: two episodes reach the demonstration threshold of three consecutive failed days.
Processing trail: source observations → one row per asset and date → gap detection → episode grouping → owned review.
The threshold is a teaching example, not an equipment safety rule. Urgent issues follow the existing immediate escalation process.
Count persistence before counting workload
A facilities team may inspect the same item several times in a day. Six failure rows could describe six isolated days, a continuous six-day problem or repeated observations of one failed day. Treating those cases as identical makes a review queue difficult to prioritise.
This SQL consecutive dates tutorial turns daily failure observations into episodes. It uses an original fictional example of routine equipment-condition checks. The result helps an operations manager distinguish repeat recording from persistence, consolidate review work and investigate recurring issues.
It does not calculate repair duration, identify the cause or prove that equipment was continuously defective between checks. Those questions need richer event and maintenance data.
Define what “consecutive” means
The rule used here
At least one failure on each adjacent calendar date belongs to the same episode for the same asset. Multiple failures on one date count as one failed day. A missing calendar date starts a new episode.
The limit of the evidence
A gap might mean a pass, no inspection or a missing extract. Failure-only data cannot distinguish them. Label the output “observed failure episodes” and retain a separate completeness check.
Use this rule for daily calendar-based checks. If inspections are due only on working days, compare consecutive dates in an approved inspection calendar instead. If the question is about consecutive inspection events, order the events themselves; two checks on one date must then remain separate.
Our input contains a stable AssetCode and a non-null FailureDate stored as SQL date. Agree the operational timezone and day boundary before deriving that date from timestamps. Casting a UTC timestamp directly to a date may put a late-night UK observation into the wrong local day during British Summer Time.
With both pass and fail observations on one day, this example uses “any failure makes it a failed day”. If your policy uses the final inspection outcome, resolve that daily state first using a reliable event order. Deduplicating failure dates cannot implement that different policy.
Run a complete, self-contained example
Use a SQL Server query window connected to a database you are authorised to query. This batch creates only a local table variable and does not modify a permanent table. It uses features available in SQL Server 2012 and later; the example avoids newer optional syntax.
Paste and run the whole batch together. The compact date literals are in unambiguous YYYYMMDD form. Asset A deliberately has two observations on 1 November.
DECLARE @Failures TABLE (
AssetCode varchar(10) NOT NULL,
FailureDate date NOT NULL
);
INSERT INTO @Failures (AssetCode, FailureDate)
VALUES
('A', '20261101'),
('A', '20261101'), -- Duplicate observation: still one failed day
('A', '20261102'),
('A', '20261103'),
('A', '20261105'),
('A', '20261106'),
('B', '20261101'),
('B', '20261103'),
('B', '20261104'),
('C', '20261102'),
('C', '20261103'),
('C', '20261104'),
('C', '20261105');
;WITH DailyFailures AS (
SELECT DISTINCT AssetCode, FailureDate
FROM @Failures
),
PreviousDay AS (
SELECT
AssetCode,
FailureDate,
LAG(FailureDate) OVER (
PARTITION BY AssetCode
ORDER BY FailureDate
) AS PreviousFailureDate
FROM DailyFailures
),
Boundaries AS (
SELECT
AssetCode,
FailureDate,
CASE
WHEN PreviousFailureDate IS NULL THEN 1
WHEN DATEDIFF(day, PreviousFailureDate, FailureDate) = 1
THEN 0
ELSE 1
END AS NewEpisode
FROM PreviousDay
),
GroupedDays AS (
SELECT
AssetCode,
FailureDate,
SUM(NewEpisode) OVER (
PARTITION BY AssetCode
ORDER BY FailureDate
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS EpisodeGroup
FROM Boundaries
)
SELECT
AssetCode,
MIN(FailureDate) AS EpisodeStart,
MAX(FailureDate) AS LastObservedFailure,
COUNT(*) AS FailedDays,
CASE WHEN COUNT(*) >= 3
THEN 'Review'
ELSE 'Routine queue'
END AS ReviewBand
FROM GroupedDays
GROUP BY AssetCode, EpisodeGroup
ORDER BY AssetCode, EpisodeStart;
Keep all episodes in the base output. Apply a review filter afterwards, or use the displayed band in a report. Removing individual dates before grouping can change the sequence you are trying to measure.
Check the result before interpreting it
| Asset | Episode start | Last observed failure | Failed days | Review band |
|---|---|---|---|---|
| A | 2026-11-01 | 2026-11-03 | 3 | Review |
| A | 2026-11-05 | 2026-11-06 | 2 | Routine queue |
| B | 2026-11-01 | 2026-11-01 | 1 | Routine queue |
| B | 2026-11-03 | 2026-11-04 | 2 | Routine queue |
| C | 2026-11-02 | 2026-11-05 | 4 | Review |
The five episode counts sum to 12 failed asset-days. The thirteenth source row is a repeated observation for A on 1 November. Asset A’s missing 4 November breaks its sequence; asset B’s missing 2 November does the same.
Do not rename the last date “resolved date”. It is simply the last observed failure in that sequence. Even an episode ending before the extract date needs a positive recovery or closure record before it can be called resolved.
Follow the four transformations
- Reduce to daily grain.
SELECT DISTINCTremoves duplicate asset-date pairs. That makes the subsequent ordering unique within each asset and prevents repeated observations inflating the day count. - Read the previous observed date.
LAGreturns the preceding row within the asset partition. The first date has no predecessor. Microsoft documents its offset-based behaviour and the role of the window ordering. [1] - Mark a boundary. A first row or a date gap other than one day receives
NewEpisode = 1. Because both operands are dates,DATEDIFF(day, ...)tests adjacent calendar dates. It counts day boundaries; it is not an elapsed-hours calculation. [2] - Accumulate the markers. The running
SUMkeeps the same group value until the next boundary. The explicitROWSframe runs from the partition start through the current row. Grouping by asset and that value then produces the episode summary. [3]
For A’s unique dates, the boundary markers are 1, 0, 0, 1, 0 and the group values are 1, 1, 1, 2, 2. The grouping restarts for every asset. B’s first date therefore cannot continue an episode belonging to A.
EpisodeGroup as a permanent maintenance-ticket identifier. Persist reviewed cases under a separate durable key and record how new evidence changes their linked dates.Test the boundaries that change the answer
Run each change against a fresh copy of the original fixture. Insert extra rows before the common table expressions.
- Duplicate test: add another A /
20261102row. The output must remain five episodes and 12 failed asset-days. - Gap test: remove C /
20261103. C must split into a one-day episode on 2 November and a two-day episode on 4–5 November. - Asset isolation: add D /
20261103. D must have its own one-day episode without changing A, B or C. - Month boundary: add E /
20261130and E /20261201. These must form one two-day episode. A month change is not a gap. - Empty input: remove the insert statement. The query must return no episodes, not a synthetic zero-day row. The reporting layer must distinguish “no failures” from an incomplete extract.
For each returned episode, verify that FailedDays = DATEDIFF(day, EpisodeStart, LastObservedFailure) + 1. Also verify that the sum of episode day counts equals the count of distinct input asset-date pairs. These checks expose lost rows, accidental duplicates and broken grouping.
A reporting start date needs its own test. Filtering away earlier history before the query can truncate an episode already in progress. To report episodes overlapping a period, group the required history first, then keep episodes whose start is on or before the period end and whose last observed failure is on or after the period start.
If you cannot load enough history to establish a true start, label the first episode as potentially truncated. A fixed lookback cannot guarantee completeness when a streak can be longer than that lookback. Record the extract cut-off too: later failures may extend the most recent episode.
Make the episode view safe to use in daily work
Operations owns the rule. Agree calendar days versus scheduled checks, the daily outcome policy and the review threshold. Keep urgent escalation independent of this analytical queue. A longer streak is evidence of persistence, not a complete measure of severity.
The data owner owns the evidence. Validate asset identity, missing dates, duplicate ingestion and late-arriving observations. Quarantine invalid source dates with a visible exception count. Retain source observation identifiers so a reviewer can open the underlying checks.
The reporting owner owns the implementation. Replace the table variable with the approved source, preserve the same daily grain and review the execution plan on representative volumes. An index beginning with asset and failure date may help this access pattern, but assess it against the actual workload and existing indexes.
Pilot with one team. Review the episode table beside the original daily log and ask users to explain a duplicate, a gap and an unresolved final date. Assign each review to a named person, with an outcome and a due date, before introducing automated notifications.
Measure the proportion of episodes with linked evidence, time spent consolidating repeated observations, reviews completed by the agreed date and discrepancies found during reconciliation. Track repeat failures after intervention separately. The query organises evidence; it does not demonstrate that a repair worked or promise a particular saving.
Is your episode report ready for a pilot?
Tick controls you can demonstrate. The first two are essential; the score is a practical self-check, not a certification.
This assessment runs in your browser and does not submit or save your answers.
Frequently asked questions
Does a missing date prove the asset recovered?
No. A missing date breaks an observed calendar-day streak, but it may represent a pass, no inspection or missing data. Recovery needs separate evidence.
Can this query count consecutive working days?
Not as written. It tests adjacent calendar dates. For scheduled working-day inspections, use an approved inspection calendar and test adjacency in that schedule.
Why remove duplicate dates before using LAG?
The unit being counted is a failed asset-day. Keeping several observations on one date would inflate counts and disrupt the one-row-per-day sequence.
Can EpisodeGroup become a permanent ticket number?
No. The running group value can change when historical data changes. Use a separate durable case identifier for operational tracking.
Technical sources
Microsoft documentation checked on 1 December 2026. The fixture, threshold and business recommendations are original illustrative material, not measured customer results.
- Microsoft Learn: LAG (Transact-SQL) — previous-row access and ordering.
- Microsoft Learn: DATEDIFF (Transact-SQL) — datepart boundary semantics.
- Microsoft Learn: SUM (Transact-SQL) — analytic aggregation and cumulative totals.