题目如下:
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([value1] int,[value2] int)
insert [tb]
select 1,12 union all
select 1,13 union all
select 1,23 union all
select 0,14 union all
select 0,15 union all
select 1,16 union all
select 0,23 union all
select 0,22 union all
select 1,21 union all
select 1,12
要求显示的结果:
value1 value2 col3
----------- ----------- -----------
1 12 1
1 13 2
1 23 3
0 14 1
0 15 2
1 16 1
0 23 1
0 22 2
1 21 1
1 12 2
****************************************
我的做法:
****************************************
declare @value1 as int,@value2 as int;
declare @prvvalue1 as int,@flag as int;
declare @result table
(
value1 int,
value2 int,
col3 int
);
declare c cursor fast_forward for
select value1,value2
from tb;
open c
fetch next from c into @value1,@value2;
select @prvvalue1 = @value1,@flag = 0;
while @@FETCH_STATUS = 0
begin
if @value1 <> @prvvalue1
select @prvvalue1 = @value1,@flag = 0;
set @flag = @flag + 1;
insert into @result values(@value1,@value2,@flag);
fetch next from c into @value1,@value2;
end
close c;
deallocate c;
select *
from @result;
【原】一道SQL题(根据一个字段值的变化,在另一个字段中计数)
最新推荐文章于 2022-12-17 10:01:39 发布