使用多个条件计算组数和组大小

时间:2015-06-15 23:44:48

标签: sql-server-2008-r2 partition

我的数据如下:

enter image description here

我需要根据生成和结束时间计算最后两列(noofgrpgrpsize)否组(Clientid计数)和组大小(每组中的客户端数)。所以我在第一个Temp表中尝试了以下内容

GrpSize= count(clientid) over (partition by begtime,endtime) else 0 end 

在第二个临时表中,我有

select
,GrpSize=sum(grpsize)
,NoofGrp=count(distinct grpsize)
From Temp1

问题是5月26日,begtimeendtime不一致。在Grp1(组1)中,所有客户端在1030开始会话并在1200(90分钟会话)结束,除了一个从11开始并在1200结束(第8行)的客户。对于此客户端,因为他/她endtime与其他客户端相同,我希望该客户端位于第一组(Grp1)中。对于第二组(Grp2),反转为真。所有客户begtime为12:30,endtime为1400但clientid=2(第9行)为begtime =1230endtime = 1300。但是,由于此客户端begtime与其他客户端相同,我希望该客户端位于第二个组(grp2)中。我的分区将创建4个组而不是2个组。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

with cte1 as (
select date1,id,ROW_NUMBER() over (order by date1) as rn
from #a
),cte2 as (
select top 1 date1,id,rn,cast('grp1' as varchar(10)) as grp ,i = 1
from cte1
union all
select b.date1,b.id,b.rn,cast('grp' + cast((case when a.id = 10 then i+1 else i end) as varchar(10)) as varchar(10)), (case when a.id = 10 then i+1 else i end)
from cte2 as a
inner join cte1 as b
on b.rn = a.rn + 1
)
select *,(case when id = 10 then 'grp' + cast(COUNT(grp) over (partition by grp) as varchar(10)) else '' end)
 from cte2
相关问题