Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Continuous Block of Dates

Author  Topic 

VentureFree
Starting Member

19 Posts

Posted - 2009-09-02 : 03:01:09
I have a table with a single date column, and I'm trying to determine the range of dates for which a specific criterion is met. Here's an example of what I mean:
CREATE TABLE [MyTestTable] (
[MyDate] [datetime] NOT NULL,
[MyCriterion] [bit] NOT NULL
)

INSERT INTO MyTestTable (MyDate,MyCriterion) VALUES ('2009-01-01',1)
INSERT INTO MyTestTable (MyDate,MyCriterion) VALUES ('2009-01-02',1)
INSERT INTO MyTestTable (MyDate,MyCriterion) VALUES ('2009-01-03',1)
INSERT INTO MyTestTable (MyDate,MyCriterion) VALUES ('2009-01-04',0)
INSERT INTO MyTestTable (MyDate,MyCriterion) VALUES ('2009-01-05',1)
INSERT INTO MyTestTable (MyDate,MyCriterion) VALUES ('2009-01-06',0)
INSERT INTO MyTestTable (MyDate,MyCriterion) VALUES ('2009-01-07',1)
INSERT INTO MyTestTable (MyDate,MyCriterion) VALUES ('2009-01-08',1)

What I would like is a select statement that returns the start and end dates for each continuous block of dates where MyCriterion = 1 (NOTE: my table has no gaps in the dates, so from the first date to the last there are no missing dates or dates with no data). So given the above data, this select statement would return the following:

StartOfBlock EndOfBlock
------------ ------------
'2009-01-01' '2009-01-03'
'2009-01-05' '2009-01-05'
'2009-01-07' '2009-01-08'

I'm guessing step one is simply a sub-query getting only those entries where MyCriterion = 1. Is there some way to detect which dates are missing then? I'm not sure that would help in determining the continuous blocks, though.

Anyway, any suggestions on how to do this, or even where to begin would be greatly appreciated.

Sachin.Nand

2937 Posts

Posted - 2009-09-02 : 03:27:05
Have a look at this.It is a great article posted by "Peso the great".

http://weblogs.sqlteam.com/peterl/archive/2009/08/21/Third-running-streak.aspx

PBUH
Go to Top of Page

VentureFree
Starting Member

19 Posts

Posted - 2009-09-02 : 04:16:26
It's not exactly the same as what I'm trying to do, but it's so close that I'm sure I'll have no problem modifying it to do what I need. Thank you very very much!
Go to Top of Page
   

- Advertisement -