I have my question altered as is viewed as vague. I have a table as below:
Id AltId DateFrom DateTo CurrentFlag Value
1 23 2015-04-01 2015-05-31 0 0
2 23 2015-05-31 Null 1 50
3 45 2015-06-01 Null 1 0
4 60 2015-07-01 Null 1 0
I want to achieve a count where Value is 0 for the past six months. Expected results:
Month Count
4 1
5 1
6 1
7 2
8 2
9 2
This is supposed to be cumulative count but the AltId ceases in a month where it changes value to anything greater than 0 like is the case with AltId 23. Cumulative count is not an issue but how to not include an AltId when it's value changes from 0.
I'm not sure if this makes sense this time around. I'm using Sql Server 2008.
I'm wondering why this script doesn't do what I expect:
declare @a table
(
id int
,altId int
,startDate date
,endDate date
,currentFlag bit
,value int
)
insert into @a
values
(1,23,'2015-04-01','2015-05-31',0,0)
,(2,23,'2015-05-31',null,1,50)
,(3,45,'2015-06-01',null,1,0)
,(4,60,'2015-07-01',null,1,0)
declare @s date =DATEADD(m, -5, convert(date, convert(varchar(6), getdate(),112) + '01')), @e date = getdate();
;with d([Month],DateKey) as
(
select month(@s) [Month],@s DateKey
union all
select
month(DateKey),dateadd(day,1,DateKey)
from
d
where d.DateKey>= @s and d.DateKey<=@e
)
select
d.Month
,count(distinct a.altId) as 'Count'
from
d
left join
@a a
on
d.dateKey between a.startDate and isnull(a.endDate,getdate())
and
a.value=0
group by
d.[Month]
option (maxrecursion 186)
Any idea?
This does the trick.
declare @a table
(
id int
,altId int
,startDate date
,endDate date
,currentFlag bit
,value int
)
insert into @a
values
(1,23,'2015-04-01','2015-05-31',0,0)
,(2,23,'2015-05-31',null,1,50)
,(3,45,'2015-06-01',null,1,0)
,(4,60,'2015-07-01',null,1,0)
declare @s date =DATEADD(m, -5, convert(date, convert(varchar(6), getdate(),112) + '01')), @e date = getdate();
select @s,@e
;with d([Month],DateKey) as
(
select month(@s) [Month],@s DateKey
union all
select
month(dateadd(day,1,DateKey)),dateadd(day,1,DateKey)
from
d
where d.DateKey>= @s and dateadd(day,1,DateKey)<=@e
)
select
d.Month
,count(distinct a.altId) as 'Count'
from
d
left join
@a a
on
d.dateKey between a.startDate and isnull(a.endDate,getdate())
and
a.value=0
group by
d.[Month]
option (maxrecursion 186)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.