我的问题被改变,因为被视为模糊。我有一张桌子如下:
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
我希望在过去的六个月里达到Value为0的计数。预期结果:
Month Count
4 1
5 1
6 1
7 2
8 2
9 2
这应该是累计计数,但AltId在一个月内停止,它将值更改为大于0的任何值,就像AltId 23的情况一样。 累积计数不是问题,但是当值从0变为0时,如何不包括AltId。
这次我不确定这是否合理。我正在使用Sql Server 2008。
我想知道为什么这个脚本不符合我的期望:
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)
有什么想法吗?
答案 0 :(得分:0)
这就是诀窍。
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)