I have a table named "MachineHealth". Here is the sample data:
Date | MachineId | IsBad |
---|---|---|
2020-01-05 | 1 | 1 |
2020-01-04 | 1 | 1 |
2020-01-03 | 1 | 1 |
2020-01-02 | 1 | 0 |
2020-01-01 | 1 | 1 |
2020-01-05 | 2 | 1 |
2020-01-04 | 2 | 1 |
2020-01-03 | 2 | 0 |
2020-01-02 | 2 | 0 |
2020-01-01 | 2 | 1 |
I want to find continuous 1 count in field IsBad
group by MachineId
, that means the number of days that a machine is continuously bad for the most recent time. For example, the query on above data should return:
MachineId | ContinuousBadDays |
---|---|
1 | 3 |
2 | 2 |
How to write this sql?
Best Answer
Assuming your duplicate
Dates
forMachineId = 1
was an accident (as Scott pointed out) something like this should be what you're after:This uses the
ROW_NUMBER()
window function to get the latestDate
no accidents occurred on per eachMachineId
in a CTE then uses that CTE to join to filter down the results to only the most recent continuous badDates
. The final query then does aGROUP BY
onMachineId
and sums theIsBad
field to get the total days (though you probably can even substitute that for aCOUNT(1)
instead if your IsBad field at most has a value of 1).