【原】一道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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值