Longest Steady Thermostat Streak
Problem
A smart-home service records every time a household's thermostat is set in the table `thermostat_log`, with the `home_id`, the `set_date`, and the `mode` chosen ('heat', 'cool', 'eco', or 'off'). A household is *steady* over a run of days when, for at least 5 consecutive calendar days, it set the thermostat exactly once per day AND chose the same mode on every one of those days. For each household that has at least one such run, return its single longest steady run: the `home_id`, the `mode` held, the run length in days as `run_length`, and the run's `start_date` and `end_date`. If a household has two runs of equal length, keep the earlier-starting one. Order the result by `run_length` descending, then by `home_id` ascending.
Tables
Example rows — the live problem includes the full dataset.
| home_id | set_date | mode |
|---|---|---|
| 1 | 2024-01-01 | heat |
| 1 | 2024-01-02 | heat |
| 1 | 2024-01-03 | heat |
Expected output
Your answer should return 2 rows with the columns home_id, mode, run_length, start_date, end_date.
Starter code (SQL)
SELECT *
FROM thermostat_log;Solve this SQL question free
Write SQL and run it instantly in your browser — even on your phone. No signup needed to try.
Solution & explanation
Create a free account to unlock the optimal solution, a step-by-step explanation, and the hidden test cases that grade your answer.
Sign up free to unlock