Sql server 如何计算2类缓慢变化维度列中某个值的出现次数?
我的问题被修改了,因为它被认为是模糊的。我的表格如下:Sql server 如何计算2类缓慢变化维度列中某个值的出现次数?,sql-server,Sql Server,我的问题被修改了,因为它被认为是模糊的。我的表格如下: 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
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
我想在过去六个月内实现一个值为0的计数。预期成果:
Month Count
4 1
5 1
6 1
7 2
8 2
9 2
这应该是累积计数,但AltId在一个月内停止,此时它将值更改为大于0的任何值,就像AltId 23的情况一样。
累积计数不是问题,但当AltId的值从0更改时,如何不包括它
我不确定这一次是否有意义。我正在使用SQLServer2008
我想知道为什么这个脚本没有达到我的预期:
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)
有什么想法吗?这就行了
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)
你的问题毫无意义。例如,你使用的术语对你的意义明显不同于其他人。更改维度不是典型的关系数据库术语。请将您的问题解释为输入和预期输出的列表。您的问题非常模糊。SCD是一种变更跟踪设计。所以你可以用count和group来做这件事。你应该发布一个原始数据的例子,以及预期的结果。我已经编辑了我的问题,我想知道它现在是否有意义。