I have a table with 3 column (id(int),date(date),Status(bool)) .
like this
id date Status
1 2012-10-18 1
1 2012-10-19 1
1 2012-10-20 0
1 2012-10-21 0
1 2012-10-22 0
1 2012-10-23 0
1 2012-10-24 1
1 2012-10-25 0
1 2012-10-26 0
1 2012-10-27 0
1 2012-10-28 1
2 2012-10-19 0
2 2012-10-20 0
2 2012-10-21 0
2 2012-10-22 1
2 2012-10-23 1
assume that date column are sequential and there is no gap between dates.
How can I find all 3 sequential zeros (in Status column) and their next day status ?
like this
id startDate endDate NextDayStatus
1 2012-10-20 2012-10-22 0
1 2012-10-21 2012-10-23 1
1 2012-10-25 2012-10-27 1
2 2012-10-19 2012-10-21 1
table creation script and sample data
CREATE TABLE [Table1](
[ID] [smallint] NOT NULL,
[Date] [date] NOT NULL,
[Status] [bit] NULL,
CONSTRAINT [PK_table1] PRIMARY KEY CLUSTERED ( [ID] ASC, [Date] ASC ) )
INSERT INTO [Table1]([ID], [Date], [Status])
SELECT 1, '2012-10-18', 1 UNION ALL
SELECT 1, '2012-10-19', 1 UNION ALL
SELECT 1, '2012-10-20', 0 UNION ALL
SELECT 1, '2012-10-21', 0 UNION ALL
SELECT 1, '2012-10-22', 0 UNION ALL
SELECT 1, '2012-10-23', 0 UNION ALL
SELECT 1, '2012-10-24', 1 UNION ALL
SELECT 1, '2012-10-25', 0 UNION ALL
SELECT 1, '2012-10-26', 0 UNION ALL
SELECT 1, '2012-10-27', 0 UNION ALL
SELECT 1, '2012-10-28', 1 UNION ALL
SELECT 2, '2012-10-19', 0 UNION ALL
SELECT 2, '2012-10-20', 0 UNION ALL
SELECT 2, '2012-10-21', 0 UNION ALL
SELECT 2, '2012-10-22', 1 UNION ALL
SELECT 2, '2012-10-23', 1
update:
- if it matters, after this step i only need to filter out the days that are first ,10th or 20th of the month
- with many thanks to Tomalak and gnb ,in my real task the number of consecutive zeros is 9 instead of 3 in this sample , so using 9 inner joins or cross apply seems inefficient