按以下方式提供数据
我希望输出如下:
我想要基于事件'X'
的额外列EventCount如果Event ='X'则为1并且如果它是同一组则递增。
提前致谢。
Zaim Raza。
答案 0 :(得分:0)
您可以使用以下代码:
create table #event
(
id int,
event varchar(10),
dates date
)
insert into #event
select 1, 'x', '1/1/2016' union all
select 1, 'y', '1/1/2016' union all
select 1, 'z', '1/1/2016' union all
select 1, 'x', '1/1/2016' union all
select 1, 'w', '1/1/2016' union all
select 2, 'x', '1/1/2016' union all
select 2, 'x', '1/1/2016' union all
select 2, 'w', '1/1/2016' union all
select 2, 'w', '1/1/2016' union all
select 2, 'm', '1/1/2016' union all
select 2, 'x', '1/1/2016'
select *,row_number() over( order by id) as txts
into #evts
from #event
select *
,(select sum(case when b.event='x' then 1 else 0 end ) from #evts b where b.txts <= a.txts and a.id = b.id) as outputs
from #evts a
希望此解决方案可以帮助您。