【原】一道SQL题(根据一个字段值的变化,在另一个字段中计数)
2011-04-27 23:19
471 查看
题目如下:
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;
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题(根据一个字段值的后四位的两两差,生成对应的数据行)
- SQL两表之间:根据一个表的字段更新另一个表的字段
- Mysql 根据一个表数据更新另一个表的某些字段(sql语句)
- sql 根据关联 用一个表的值修改另一个表对应字段的值
- 【数据库】SQL两表之间:根据一个表的字段更新另一个表的字段
- SQL 根据一个表更新另一个表的字段
- SQL两表之间:根据一个表的字段更新另一个表的字段
- SQL两表之间:根据一个表的字段更新另一个表的字段
- SQL技巧两则:选择一个表的字段插入另一个表,根据其它表的字段更新本表内容
- SQL - 根据关联,用一个表的值修改另一个表对应字段的值
- mysql把一个表的字段update成另一个表的字段根据id
- SQL 根据一个表更新另一个表的内容
- 根据一个表里的字段查询另一个表里的另一个字段,再将查询的字段添加到第一个表里
- 多对多关系中,根据其中一个字段查询另一个字段(createAlias)
- Sql 把一个表中某个字段的数据插入到另一个表中
- Sql-Server触发器,根据条件匹配另一个表中的字段
- sql中,将同一个表中两个类型一样的字段的值互换 以及 将同一个表中的一个字段的值复制给另一个字段
- 根据一个字段录入值带出另一个字段值时,有空值的C#.NET处理
- sql 一个表的字段更新至另一个字段的方法
- SQL-----将一个表中的字段update到另一个表中的字段