27,579
社区成员
发帖
与我相关
我的任务
分享
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([cardid] int,[status] int,[time] varchar(20))
insert [tb]
select 1010,0,'2009-10-25 01:00:00' union all
select 1010,0,'2009-10-25 01:01:00' union all
select 1010,0,'2009-10-25 01:02:00' union all
select 1011,1,'2009-10-25 01:03:00' union all
select 1011,1,'2009-10-25 01:04:00' union all
select 1011,1,'2009-10-25 01:05:00' union all
select 1011,1,'2009-10-25 01:06:00' union all
select 1012,0,'2009-10-25 01:07:00' union all
select 1012,0,'2009-10-25 01:08:00' union all
select 1012,0,'2009-10-25 01:09:00' union all
select 1013,0,'2009-10-25 01:10:00' union all
select 1013,1,'2009-10-25 01:11:00' union all
select 1013,1,'2009-10-25 01:12:00' union all
select 1013,1,'2009-10-25 01:13:00' union all
select 1013,0,'2009-10-25 01:14:00' union all
select 1013,1,'2009-10-25 01:15:00' union all
select 1013,1,'2009-10-25 01:16:00' union all
select 1013,0,'2009-10-25 01:17:00' union all
select 1013,1,'2009-10-25 01:18:00' union all
select 1013,1,'2009-10-25 01:19:00' union all
select 1013,1,'2009-10-25 01:20:00' union all
select 1013,1,'2009-10-25 01:21:00' union all
select 1013,1,'2009-10-25 01:22:00' union all
select 1013,1,'2009-10-25 01:23:00'
;with t as(
select cardid,status,time,
ROW_NUMBER() over (order by time)-
ROW_NUMBER() over (partition by status order by time) grp
from tb
)
select cardid,status,time,
(case status when 1
then ROW_NUMBER() over (partition by status,grp order by time)
else 0 end) [count]
from t order by time;
/*
1010 0 2009-10-25 01:00:00 0
1010 0 2009-10-25 01:01:00 0
1010 0 2009-10-25 01:02:00 0
1011 1 2009-10-25 01:03:00 1
1011 1 2009-10-25 01:04:00 2
1011 1 2009-10-25 01:05:00 3
1011 1 2009-10-25 01:06:00 4
1012 0 2009-10-25 01:07:00 0
1012 0 2009-10-25 01:08:00 0
1012 0 2009-10-25 01:09:00 0
1013 0 2009-10-25 01:10:00 0
1013 1 2009-10-25 01:11:00 1
1013 1 2009-10-25 01:12:00 2
1013 1 2009-10-25 01:13:00 3
1013 0 2009-10-25 01:14:00 0
1013 1 2009-10-25 01:15:00 1
1013 1 2009-10-25 01:16:00 2
1013 0 2009-10-25 01:17:00 0
1013 1 2009-10-25 01:18:00 1
1013 1 2009-10-25 01:19:00 2
1013 1 2009-10-25 01:20:00 3
1013 1 2009-10-25 01:21:00 4
1013 1 2009-10-25 01:22:00 5
1013 1 2009-10-25 01:23:00 6
*/