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
 General SQL Server Forums
 New to SQL Server Programming
 Return all dates open in given month

Author  Topic 

madlan
Starting Member

5 Posts

Posted - 2010-12-10 : 20:45:35
Hi All,

I little select query I thought would be easy....

I'm trying to return a rolling 13 month list of all records from a table that have 'active', defined as (for the select month) An Open date in or before the select month and null Closed date or Closed after the select month.

I've come up with:

select * from [Knowledge_Base]
where Date_Opened <= '2010-09-30'
and Closed Is NULL or Closed > '2010-09-30'


Which is great for one month at a time... How do I span this across a year in a single statement? I tried a CASE, using count to tally up the results, but this will only work for records within the select month.

Test data:

Issue Date_Opened Date_Closed
Test1 2010-09-30 NULL
Test2 2010-09-28 2010-09-30
Test3 2010-07-22 NULL
Test4 2010-08-13 NULL
Test5 2009-09-26 NULL

Resulting in:

MONTH Open Issues
November 10
December 12
January 11
February 22
etc...

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2010-12-10 : 22:58:51
One way is to join to a date table with one date for each month.

create table #Month
(
MonthStartDate datetime not null,
NextMonthStartDate datetime not null primary key clustered
)

-- Create table of month start dates
insert into #Month
select
MonthStartDate = dateadd(mm,datediff(mm,0,getdate())+a.number,0),
NextMonthStartDate = dateadd(mm,datediff(mm,0,getdate())+a.number+1,0)
from
-- Number Table Function available here
-- http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=47685
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=47685
dbo.F_TABLE_NUMBER_RANGE(-12,0) a
order by
a.number


select
b.MonthStartDate,
a.*
from
[Knowledge_Base] a
join
#t b
on
a.Date_Opened < b.NextMonthStartDate and
(a.Closed >= b.NextMonthStartDate or a.Closed is null )
order by
b.MonthStartDate





CODO ERGO SUM
Go to Top of Page
   

- Advertisement -