【原】一道SQL題(根據一個字段值的變化,在另一個字段中計數)

題目如下:
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;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章