Report Contiguous Dates - Problem
A system runs one task every day, and each task can either fail or succeed. You have two tables tracking these outcomes:
- Failed: Contains dates when tasks failed
- Succeeded: Contains dates when tasks succeeded
Write a SQL query to report contiguous periods of the same outcome (failed or succeeded) for the year 2019. For each continuous interval, return:
period_state: Either 'failed' or 'succeeded'start_date: First date of the intervalend_date: Last date of the interval
Return results ordered by start_date.
Table Schema
Failed
| Column Name | Type | Description |
|---|---|---|
fail_date
PK
|
date | Date when task failed |
Primary Key: fail_date
Succeeded
| Column Name | Type | Description |
|---|---|---|
success_date
PK
|
date | Date when task succeeded |
Primary Key: success_date
Input & Output
Example 1 — Mixed Success and Failure Periods
Input Tables:
Failed
| fail_date |
|---|
| 2019-01-01 |
| 2019-01-02 |
| 2019-01-05 |
Succeeded
| success_date |
|---|
| 2019-01-03 |
| 2019-01-04 |
| 2019-01-06 |
Output:
| period_state | start_date | end_date |
|---|---|---|
| failed | 2019-01-01 | 2019-01-02 |
| succeeded | 2019-01-03 | 2019-01-04 |
| failed | 2019-01-05 | 2019-01-05 |
| succeeded | 2019-01-06 | 2019-01-06 |
💡 Note:
The system shows alternating periods: 2 consecutive failed days (Jan 1-2), then 2 successful days (Jan 3-4), then single-day periods. Each contiguous sequence of the same state forms one period.
Example 2 — Long Contiguous Periods
Input Tables:
Failed
| fail_date |
|---|
| 2019-01-01 |
| 2019-01-02 |
| 2019-01-03 |
Succeeded
| success_date |
|---|
| 2019-01-04 |
| 2019-01-05 |
Output:
| period_state | start_date | end_date |
|---|---|---|
| failed | 2019-01-01 | 2019-01-03 |
| succeeded | 2019-01-04 | 2019-01-05 |
💡 Note:
Shows longer contiguous periods: a 3-day failure period followed by a 2-day success period. The window function correctly identifies these as separate groups.
Constraints
-
fail_dateandsuccess_dateare within the range[2019-01-01, 2019-12-31] - Each date appears at most once across both tables
- The system runs exactly one task per day
Visualization
Tap to expand
Understanding the Visualization
1
Input Tables
Failed and Succeeded date tables
2
Union & Group
Combine tables and identify contiguous periods
3
Output
Period states with start/end dates
Key Takeaway
🎯 Key Insight: Use ROW_NUMBER() arithmetic to detect group boundaries in sequential data
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code