Please help me generate the following query, which I have been struggling with for some time. Lets say that I have a simple table with a month number and information on whether there were any unsuccessful events in this particular month.
Below is a script to generate sample data:
WITH DATA(Month, Success) AS ( SELECT 1, 0 UNION ALL SELECT 2, 0 UNION ALL SELECT 3, 0 UNION ALL SELECT 4, 1 UNION ALL SELECT 5, 1 UNION ALL SELECT 6, 0 UNION ALL SELECT 7, 0 UNION ALL SELECT 8, 1 UNION ALL SELECT 9, 0 UNION ALL SELECT 10, 1 UNION ALL SELECT 11, 0 UNION ALL SELECT 12, 1 UNION ALL SELECT 13, 0 UNION ALL SELECT 14, 1 UNION ALL SELECT 15, 0 UNION ALL SELECT 16, 1 UNION ALL SELECT 17, 0 UNION ALL SELECT 18, 0 )
Given the definition of "repeated failure":
If a failure in the event occurs for at least 4 months within any 6 months, then the last month with such a failure is a “repeated failure”, my request should return the following result
Month Success RepeatedFailure 1 0 2 0 3 0 4 1 5 1 6 0 R1 7 0 R2 8 1 9 0 10 1 11 0 R3 12 1 13 0 14 1 15 0 16 1 17 0 18 0 R1
Where:
- R1 is the 1st second failure in month 6 (4 failures in the last 6 months).
- R2 -2nd second failure in month 7 (4 failures in the last 6 months).
- R3 -3rd repeated failure in month No. 11 (4 failures in the last 6 months).
R1 is the first 1st repeated failure in month No. 18, because repeated failures must be numbered again from the very beginning, when a new repeated failure occurs for the first time in the last 6 reporting periods.
Repeated failures are numbered sequentially, because based on its number, I should apply the appropriate factor:
- 1st second failure - X2
- 2nd second failure - X4
- 3rd and more repeated failure -X5.